Flash/AS3 - preload or stream embedded sounds - actionscript-3

I'm currently working on a project in flashdevelop and I want to include some music. I'm building a game, so multiple files are not an option. Currently all resources are embedded and a simple preloader loads everything (like the flashdevelop default preloader).
I don't want to load the music at the beginning, I'd rather like to stream it when required.
Is it possible to stream embedded sounds?
If not, is it possible to embed these files inside the .swf file and load them later on?
Thanks in advance!

You can do two things. One is to start loading the sounds after the initial loading finishes and save them in a Dictionary maybe. Second is to export a RSL (Runtime Shared Library) from Flash which is a SWF file which you can then load and have access to all the classes defined there.
In the first approach you basically load every sound like this and save them to dictionary:
import flash.media.Sound;
import flash.events.Event;
import flash.net.URLRequest;
import flash.utils.Dictionary;
var mSounds:Dictionary = new Dictionary();
function loadSound(url:String, soundName:String)
{
var sound:Sound = new Sound();
sound.addEventListener(Event.COMPLETE, onSoundLoadComplete);
sound.load(new URLRequest(url));
function onSoundLoadComplete(e:Event):void
{
sound.removeEventListener(Event.COMPLETE, onSoundLoadComplete);
trace(soundName,"Sound Loaded");
mSounds[soundName] = sound; // save it to dictionary
// then you can load it from dictionary
// using the name you assigned
if(mSounds["crystalised"])
(mSounds["crystalised"] as Sound).play();
}
}
loadSound("C:\\Users\\Gio\\Desktop\\Crystalised.mp3", "crystalised");
In the second approach you have to do more steps, but you load it once. I'll list the steps here:
Make a new Flash Document (FLA)
Import all the sounds you need to the library
In the properties menu of each sound select the Actionscript tab and tick the Export for Runtime Sharing checkbox and fill in the name for output SWF
After you publish this FLA you can load it in your application or game and use it like this:
import flash.display.Loader;
import flash.system.LoaderContext;
import flash.system.ApplicationDomain;
import flash.system.SecurityDomain;
import flash.events.Event;
import flash.net.URLRequest;
import flash.media.Sound;
import flash.utils.getDefinitionByName;
function loadRSL(url:String):void
{
var loader:Loader = new Loader();
var context:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onRSLLoadComplete);
loader.load(new URLRequest(url), context);
function onRSLLoadComplete(e:Event):void
{
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onRSLLoadComplete);
trace("RSL Loaded");
// creating a new instance of the sound which is defined in RSL
var soundClass:Class = getDefinitionByName("Crystalised") as Class;
var sound:Sound = (new soundClass() as Sound);
sound.play();
}
}
loadRSL("SoundLibrary.swf");

Related

ActionScript 3.0 sound not working

So having trouble making sound on keyboard press
I have the imports:
import flash.net.URLRequest;
import flash.media.Sound;
I have the variables
private var soundDownRequest:URLRequest = new URLRequest ("SoundDown.mp3");
private var downSound:Sound = new Sound (soundDownRequest);
and the event listener
private function keyDownHandler(evt:KeyboardEvent):void
{
if (evt.keyCode == 40)//ascii for down arrow
{
downSound.play();
}
}
The sound folder is in the same folder as the .as, its also in the library of the fla, yet it still doesn't work. Any idea why?
Thank you.
Update:
I got the sound to work but not using the external method I was trying to do above.
Had to do it internally.
so you need:
import flash.media.SoundChannel;
-Then you need to make sure your sound file is in your fla library.
once its in the library
-Right click > properties
-Select the Action Script Tab
-Check "export for action script"
-Give the class a name in accordance to the sound
-press ok
add this variable (your will be different):
private var downSound:TheDownSound = new TheDownSound();
downsound is the selected name of the variable, and TheDownSound is the name of the class (the one made earlier for the sound file)
then add this to where you want the sound to play:
var myDownSound:SoundChannel = downSound.play();
Do this if you cant get it working externally like me.
for a better explanation watch this guys youtube video:
https://www.youtube.com/watch?v=SZpwppe7yGs
Your code is working perfectly ok if you put your .mp3 file in the same folder as the output .swf, not near the class .as source file (because its the swf file loading the sound, so the path must be relative to it)
public class ASEntryPoint extends Sprite {
private var soundDownRequest:URLRequest = new URLRequest ("click.mp3");
private var downSound:Sound = new Sound (soundDownRequest);
public function ASEntryPoint() {
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
}
private function keyDownHandler(evt:KeyboardEvent):void{
if (evt.keyCode == 40) {
downSound.play();
}
}
}
You need to load the external file, which is asynchronous operation. Then you track the loading event and if it all goes normally you can play your loaded sound.
import flash.events.SecurityErrorEvent;
import flash.events.IOErrorEvent;
import flash.events.Event;
import flash.net.URLRequest;
import flash.media.Sound;
import flash.media.SoundChannel;
// Keep the sound loader from being garbage collected.
var soundLoader:Sound;
function loadSound(url:String):void
{
var aRequest:URLRequest = new URLRequest(url);
soundLoader = new Sound();
// Handle the normal loading.
soundLoader.addEventListener(Event.COMPLETE, onLoaded);
// Handle the error cases.
soundLoader.addEventListener(IOErrorEvent.IO_ERROR, onError, false, 0, true);
soundLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError, false, 0, true);
soundLoader.load(aRequest);
}
var audioChannel:SoundChannel;
function onLoaded(e:Event):void
{
// Sound is available here for playback.
audioChannel = soundLoader.play();
}
function onError(e:Event):void
{
trace(e);
}
You can also handle your sound as a streaming audio, but I worked with that years ago in AS2 so I cannot help here. Still, internet suggests a link: http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7d22.html

How to set JPG type of image screenshot saved from flash using Actionscript 3?

I have a problem when i wanna save screenshot entire flash stage using ActionScript 3. when i click button that use function SimpanGbr it's works for saving image with name "NamaGambar" but without type of JPG image. How to save image with it's type. I use these codes:
stop();
import flash.events.MouseEvent;
import flash.system.fscommand;
import flash.display.DisplayObject;
import flash.display.MovieClip;
import com.adobe.images.JPGEncoder;
stage.displayState = StageDisplayState.FULL_SCREEN;
exit.addEventListener(MouseEvent.CLICK,keluar);
function keluar(event:MouseEvent):void
{
fscommand("quit");
}
function SimpanGbr(e:MouseEvent):void {
var qImageData:BitmapData = new BitmapData(800, 600);
qImageData.draw(stage);
var qEncoder:JPGEncoder = new JPGEncoder(100);
var qBytes:ByteArray = qEncoder.encode(qImageData);
var qFile:FileReference = new FileReference();
var nama:String="NamaGambar";
qFile.save(qBytes, nama+".jpg");
}
You can do so using this library.
After downloading copy the source files (the com folder) on to your Class path or your application root directory. Apart from the JPEGEncoder, this library is packaged with a lot of other classes related to Hasing, Text, Date etc.
This is how we save an image from a flash movie to a local machine.
1) Create a BitmapData object out of the MovieClip or the Loader.
2) Encode the BitmapData using the JPEGEncoder and form a ByteArray.
3) Use FileReference.save() to download the image on to the User machine.
See an example:
Create a blank Flash movie and name it as “ImageSave.fla”. In the same folder create “ImageSave.as” file and copy the below code in to it. You need the “com” folder copied from the as3corelib to this folder. I have a button on the stage named “save_mc” which triggers the saveImage function.
package {
import flash.display.MovieClip;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.utils.ByteArray;
import flash.net.FileReference;
import flash.net.FileFilter;
import flash.events.*;
import flash.net.URLLoader;
import flash.net.URLRequest;
import com.adobe.images.JPGEncoder;
public class ImageSave extends MovieClip {
private var imgFile:URLRequest;
private var img:MovieClip;
private var imgLoader:Loader;
private var file:FileReference;
public function ImageSave() {
imgFile = new URLRequest("coffee.jpg"); //change it to your image path
imgLoader = new Loader();
imgLoader.load(imgFile);
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
save_mc.addEventListener(MouseEvent.CLICK, saveImage);
}
private function onLoaded(evt:Event):void {
imgLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoaded);
imgLoader.cacheAsBitmap = true;
addChild(imgLoader);
}
function saveImage(e:MouseEvent):void {
var myBitmapData:BitmapData = new BitmapData(imgLoader.width, imgLoader.height);
myBitmapData.draw(imgLoader);
var jpgEncoder:JPGEncoder = new JPGEncoder(80);
var imgByteData:ByteArray = jpgEncoder.encode(myBitmapData);
file = new FileReference();
file.browse(new Array(new FileFilter("Images (*.jpg, *.jpeg)", "*.jpg;*.jpeg")));
file.save(imgByteData, "test.jpg");
}
}
}
For your convenience you can download a working copy of this sample here.

Embedding an SWF animation at a specific location in an AS3 project

I'm doing a project in AS3 (no external libraries or Flex) and I need to embed an explosion animation over a tile when it gets destroyed. I have a small explosion animation but I don't know how I can get it to play at a specific location. Is there a way to do this? I've tried embedding it like so:
[Embed(source="../assets/64x48.swf", mimeType="application/octet-stream")] private var Explosion:Class
var explosion:MovieClip;
explosion = new Explosion();
explosion.play();
but this doesn't seem to do anything. If not an SWF, I also have a sprite sheet of an explosion I could use, but I'm not sure how to animate a sprite without using an external library.
Approach within your swf Movieclip you want to play, you must perform the following. swf convert to bytearray after, it must be restored.
EDIT
I checked your swf file. however, your swf file contents not MovieClip, but AVM1Movie file. so It is quite difficult to directly embedded. because AVM1Movie file convert to MovieClip Algorithm. but don't worry. using a ForcibileLoader easily available.
download a ForcibileLoader
original ForcibileLoader here
refer a following code. I tested great work.
package
{
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.getTimer;
import org.libspark.utils.ForcibleLoader;
public class TestProject2 extends Sprite
{
private var loader:Loader = new Loader();
private var mc:MovieClip;
public function TestProjec2t()
{
var fLoader:ForcibleLoader = new ForcibleLoader(loader);
fLoader.load(new URLRequest("../asset/64x48.swf"));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSwfLoaded);
this.addChild(loader);
}
private function onSwfLoaded(e:Event):void
{
trace(e.currentTarget.content);
mc = e.currentTarget.content as MovieClip;
mc.x = Math.random() * stage.stageWidth;
mc.y = Math.random() * stage.stageHeight;
mc.gotoAndPlay(1);
}
}
}

Red5 and AS3 - file "Mystream" is deleted (not recording)

This my first time using StackExchange so I apologize if I miss anything.
I am trying to create a AS3 Flash that will record a video using a webcam and RED5 media server; I am stuck (I am not a programmer, more of a computer handyman that does everything).
The example that comes with RED5 works fine (though is in AS2 and I could not, for some reason, make certain things I need to do work), but my code doesnt seem to record the stream as there is not file, the RED5 console only says:
[INFO] [NioProcessor-3] org.red5.server.adapter.ApplicationAdapter - File lecture.flv was deleted
here is the code so far. (updated 09/07/12)
import flash.display.Sprite;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Camera;
import flash.events.MouseEvent;
import flash.media.Microphone;
import flash.events.*;
import flash.media.Video;
var _cam:Camera
var _mic:Microphone
// create basic netConnection object
var _nc:NetConnection = new NetConnection();
_nc.client = this
// connect to the local Red5 server
_nc.connect("rtmp://localhost/myapp");
_nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
//Add listeners for buttons
record_btn.addEventListener( MouseEvent.CLICK, recordvid );
stop_btn.addEventListener( MouseEvent.CLICK, stopvideo );
//submit_btn.addEventListener( MouseEvent.CLICK, onSubmit );
//Listeners
function netStatusHandler(event:NetStatusEvent):void{
trace("start netstatus handler");
if (event.info.code == "NetConnection.Connect.Success"){
attachCamera();
}
}
function attachCamera(e:Event = null):void {
trace("attach");
//Attach Camera to field
_cam=Camera.getCamera();
_mic=Microphone.getMicrophone()
vid.attachCamera(_cam);
}
function stopvideo(e:MouseEvent):void {
//_ns.close();
}
function recordvid(e:MouseEvent):void {
var _ns:NetStream = new NetStream(_nc);
trace("publish");
_ns.attachCamera(_cam);
_ns.attachAudio(_mic);
_ns.publish("lecture", "record");
}
You have to connect & wait for the successful status before publishing the stream.
For Example :
var nc:NetConnection = new NetConnection();
nc.connect("rtmp://fms.example.com/lectureseries");
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
function netStatusHandler(event:NetStatusEvent):void{
if (event.info.code == "NetConnection.Connect.Success"){
var ns:NetStream = new NetStream(nc);
ns.publish("lecture", "record");
}
}
Have a look at the Netstream documentation to learn more.
I just found the answer thru extreme googleing, I needed to declare the Netstream variable outside the function; otherwise the "publish" video was "empty" as the garbage collector was destroying my variable at some point.
so outside a function I declare
var _ns:NetStream;
and inside the function I declare:
function recordvid(e:MouseEvent):void {
_ns = new NetStream(_nc);
_ns.attachCamera(_cam);
_ns.attachAudio(_mic);
_ns.publish("lecture", "record");
Awesomely enough, I found the answer right here in stackoverflow

loading external movie as2 wrapper

Load AS2 SWF Into AS3 SWF and pass vars in URL
I'm trying to load in a as3 file an external as2 swf file (of which I dont have access to fla file). According to the explanation given in the link above, the solution would be to use a as2 wrapper to the original as2 file (and establish a localconnection between the the as3 and as2 files). I've tried to do that, but although the movie seems to load in my as3 file, it doesnt start, doesnt play and gets stuck in the first frame. How do I play the movie (as well as load it)? Thanks for your help.
My as3 file is:
import com.gskinner.utils.SWFBridgeAS3;
var loader = new Loader()
loader.load(new URLRequest("as2_test.swf"));
addChild(loader);
var sb1:SWFBridgeAS3 = new SWFBridgeAS3("test",this);
my as2 file is:
import com.gskinner.utils.SWFBridgeAS2;
var sb1 = new SWFBridgeAS2("test",this);
sb1.addEventListener("connect",this);
var loader:MovieClipLoader = new MovieClipLoader();
loader.addListener(this);
loader.loadClip("digestive.swf", mainLoader_mc);
EDIT: I keep having this problem. This is what I have so far:
as2 file - as2test.fla (this needs to download another as2 file -digestive.sfw and acts as wrapper to establish connection between the original as2 file and the main as3 file)
import com.gskinner.utils.SWFBridgeAS2;
var sb1 = new SWFBridgeAS2("test",this);
sb1.addEventListener("connect",this);
var my_pb:mx.controls.ProgressBar;
my_pb.mode = "manual";
this.createEmptyMovieClip("img_mc22", 999);
var my_mcl:MovieClipLoader = new MovieClipLoader();
var mclListener:Object = new Object();
mclListener.onLoadStart = function(target_mc:MovieClip):Void {
my_pb.label = "loading: " + target_mc._name;
};
mclListener.onLoadProgress = function(target_mc:MovieClip, numBytesLoaded:Number, numBytesTotal:Number):Void {
var pctLoaded:Number = Math.ceil(100 * (numBytesLoaded / numBytesTotal));
my_pb.setProgress(numBytesLoaded, numBytesTotal);
trace(pctLoaded);
};
my_mcl.addListener(mclListener);
my_mcl.loadClip("digestive.swf", img_mc22);
stop();
as3 file (this plays the as2 wrapper):
import flash.net.URLRequest;
import flash.display.Loader;
import flash.events.Event;
import flash.events.ProgressEvent;
function startLoad()
{
var mLoader:Loader = new Loader();
var mRequest:URLRequest = new URLRequest("as2test.swf");
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteHandler);
mLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgressHandler);
mLoader.load(mRequest);
}
function onCompleteHandler(loadEvent:Event)
{
addChild(loadEvent.currentTarget.content);
}
function onProgressHandler(mProgress:ProgressEvent)
{
var percent:Number = mProgress.bytesLoaded/mProgress.bytesTotal;
trace(percent);
}
startLoad();
stop();
In the as2 wrapper file, the original movie plays until a certain frame; in the as3 file, the as2 wrapper file only plays the first frame. What do I have to do?????