flash as3 and external text config file - actionscript-3

My goal was to have an external text file config for a client. I didnt want to go through a crazy xml thing, I just wanted it to be simple to change.
I started with a urlLoader, and was able to dynamically generate an object no problem. This is the function which parses and sets the properties of the object.
function onLoaded(e:Event):void//initializes the config
{
var myString = String(e.target.data);
//trace(e.target.data);
//trace(myString);
var propsArray:Array = myString.split("\n");
for (var i = 0; i < propsArray.length; i++){
var thisLine:Array = propsArray[i].split("=");
var thisPropName:String = thisLine[0];
thisPropName = thisPropName.replace(rex,'');
var thisPropValue:String = thisLine[1];
thisPropValue = thisPropValue.replace(rex,'');
trace("thePropName is: " + thisPropName);
trace("thePropValue is: " + thisPropValue);
config[thisPropName] = thisPropValue;
}
}
The text file would just look something like:
gateway = "http://thePathto/theFile.php
toast = sonofabitch
timer = 5000
xSpeed = 5.0
That way, I could just put a little bit of as3 code in, type what things I wanted configured, then all I would have to do was type config.timer and
var myTimer:Timer = new Timer(Number(config.timer));
I think the problem is load order and scope. The config.timer is not created yet, so the timer is unable to access the value of the config.timer.

I'd look at using XML in future projects of this nature, however to answer your question:
I think the problem is load order and scope. The config.timer is not created yet, so the timer is unable to access the value of the config.timer.
Correct, you will need to initialize your Timer within the onLoaded() method, as the data will be received asynchronously and is not available until this happens.

ok not long ago i had created a download manager that uses this exact concept.
The link below will take you straight to the website where you can download the full swf including my source files. also this website is a good place for resources
http://ffiles.com/flash/web_applications_and_data/dynamic_download_manager_3529.html
Below is my loader:
addEventListener(Event.ENTER_FRAME, update);
var myLoader:URLLoader = new URLLoader();
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
myLoader.load(new URLRequest("settings.txt"));
myLoader.addEventListener(Event.COMPLETE, onDataLoad);
function onDataLoad(evt:Event)
{
box1.text = evt.target.data.Id_1;
box2.text = evt.target.data.Id_2;
box3.text = evt.target.data.Id_3;
box4.text = evt.target.data.Id_4;
box5.text = evt.target.data.Id_5;
}
Add some dynamic text boxes to stage and name them "box1, box2 ect..."
Now creat your text file:
Id_1=this is what ever you want
&Id_2=this is what ever you want
&Id_3=this is what ever you want
&Id_4=this is what ever you want
&Id_5=this is what ever you want
Hope this helps.

Related

Getting Bitmap from Video decoded with Nestream AppendBytes (AS3)?

I am wondering if someone who has handled NetStream.appendBytes in Flash knows how to get the bitmapData from a decoded video frame? I have already looked at this question but that is from 3 years ago and the more recent comment/answer seems to be gone. In 2014 has anyone managed to turn those bytes into a bitmap? I am working with Flash Player 11.8 and this is not a desktop/AIR app.
In the image below I can do steps 1) and 2) but there's a brick wall at step 3)
The problem is that simply using bitmapdata.draw(video_container); does not work but instead it throws a Policy File error even though I am using a byteArray (from local video file in the same directory as the SWF). No internet is even involved but Flash tells me that "No Policy File granted permission from the server" or such nonsense. I think the error is just a bail-out insteading of straight up saying "You are not allowed to do this.."
I have tried: trying to appease this Crossdomain.xml issue anyway and looking into all known security/domain settings. I came to the conclusion that the error is not the problem but a side effect of the issue.. The issue here being that: Flash Player is aware of the SWF's location and of any files local to it. That's okay when you pass a String as URL etc but when the Netstream data is not local to the SWF domain then it becomes a Policy File issue. Problem is my data is in the Memory not in a folder like the SWF and therefore cannot alllow bitmapData.draw since it cannot "police" an array of bytes, any known fixes for this?... (I can't even say the words I really wanted to use).
What I am trying to achieve: Is to essentially use Netstream as an H.263 or H.264 image decoder in the same way Loader is a JPEG-to-Bitmap decoder or LoadCompressed.. is an MP3-to-PCM decoder. You know, access the raw material (here RGB pixels), apply some effects functions and then send to screen or save to disk.
I know it is a little late, but I think I found a solution for your problem.
So, to avoid the Security sandbox violation #2123 Error, you have just to do like this :
// ...
net_stream.play(null);
net_stream.play('');
// ...
Hope that can help.
I know this question is a couple months old, but I wanted to post the correct answer (because I just had this problem as well and other will too).
Correct answer:
It's a bug that has been open at adobe for almost 2 years
Link to the bug on Adobe
Work Around until the bug gets fixed (I am using this and it works great):
Workaround using Sprite and graphics
To take a snapshot from a video stream we don't need NetStream.appendBytes which inject data into a NetStream object.
For that we can use BitmapData.draw which has some security constraints. That's why in many times we get a flash security error. About that, Adobe said :
"... This method is supported over RTMP in Flash Player 9.0.115.0 and later and in Adobe AIR. You can control access to streams on Flash Media Server in a server-side script. For more information, see the Client.audioSampleAccess and Client.videoSampleAccess properties in Server-Side ActionScript Language Reference for Adobe Flash Media Server. If the source object and (in the case of a Sprite or MovieClip object) all of its child objects do not come from the same domain as the caller, or are not in a content that is accessible to the caller by having called the Security.allowDomain() method, a call to the draw() throws a SecurityError exception. This restriction does not apply to AIR content in the application security sandbox. ...".
For crossdomain file creation and some other security config for AMS server, you can take a look on this post : Crossdomain Video Snapshot - Fixing BitmapData.draw() Security Sandbox Violation.
After allowing our script to get data from our video stream, we can pass to the code.
I wrote a code that play a video stream ( rtmp or http ) and take a snapshot to show it in the stage or save it as a file after applying a pixel effect :
const server:String = null; //'rtmp://localhost/vod'
const stream:String = 'stream'; // 'mp4:big_buck_bunny_480p_h264.mp4';
var nc:NetConnection;
var ns:NetStream;
var video:Video;
const jpg_quality:int = 80;
const px_size:int = 10;
nc = new NetConnection();
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, function(e:AsyncErrorEvent):void{});
nc.addEventListener(NetStatusEvent.NET_STATUS, function(e:NetStatusEvent):void{
if(e.info.code == 'NetConnection.Connect.Success'){
ns = new NetStream(nc);
ns.addEventListener(NetStatusEvent.NET_STATUS, function(e:NetStatusEvent):void{});
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, function(e:AsyncErrorEvent):void{});
video = new Video(320, 180);
video.x = video.y = 10;
video.attachNetStream(ns);
addChild(video);
ns.play(stream);
}
})
nc.connect(server);
btn_show.addEventListener(
MouseEvent.CLICK,
function(e:MouseEvent): void{
var bmp:Bitmap = pixelate(video, px_size);
bmp.x = 10;
bmp.y = 220;
addChild(bmp);
}
)
btn_save.addEventListener(
MouseEvent.CLICK,
function(e:MouseEvent): void{
var bmp:Bitmap = pixelate(video, px_size);
var jpg_encoder:JPGEncoder = new JPGEncoder(80);
var jpg_stream:ByteArray = jpg_encoder.encode(bmp.bitmapData);
var file:FileReference = new FileReference();
file.save(jpg_stream, 'snapshot_'+int(ns.time)+'.jpg');
}
)
function pixelate(target:DisplayObject, px_size:uint):Bitmap {
var i:uint, j:uint = 0;
var s:uint = px_size;
var d:DisplayObject = target;
var w:uint = d.width;
var h:uint = d.height;
var bmd_src:BitmapData = new BitmapData(w, h);
bmd_src.draw(d);
var bmd_final:BitmapData = new BitmapData(w, h);
var rec:Rectangle = new Rectangle();
rec.width = rec.height = s;
for (i = 0; i < w; i += s){
for (j = 0; j < h; j += s){
rec.x = i;
rec.y = j;
bmd_final.fillRect(rec, bmd_src.getPixel32(i, j));
}
}
bmd_src.dispose();
bmd_src = null;
return new Bitmap(bmd_final);
}
Of course, this is just a simple example to show the manner to get a snapshot from a video stream, you should adapt and improve it to your needs ...
I hope all that can help you.

Using a Numeric Stepper from one Flash file to affect gamespeed in an external Flash file? Actionscript 3.0

Currently I have an intro screen to my flash file which has two objects.
A button which will load an external flash file using:
var myLoader:Loader = new Loader();
var url:URLRequest = new URLRequest("flashgame.swf");
The second thing is a Numeric Stepper, which will be from 1 to 10. If the user selects a number e.g. 3 then the game speed I have set in the flashgame.swf should be changed
Such as:
var gameSpeed:uint = 10 * numericStepper.value;
But I think my problem is coming into place because the stepper and gamespeed are from different files.
Anyone got any idea please?
I have also tried creating a stepper in the game file and used this code:
var gameLevel:NumericStepper = new NumericStepper();
gameLevel.maximum = 10;
gameLevel.minimum = 1;
addChild(gameLevel);
var gameSpeed:uint = 10 * gameLevel.value;
For some reason the stepper just flashes on the stage, no errors come up and the game doesn't work
When you execute you code, the stepper has no chance to wait for user input.
There is no time between theese two instructions.
addChild(gameLevel);
var gameSpeed:uint = 10 * gameLevel.value;
You should wait for user input in your NumericStepper, and then, on user event, set the game speed.
Edit: Yeah I know it's kinda sad to type out all this code (especially since some people wouldn't even be grateful enough to say thanks) but I think this question is important enough to justify the code as it may be helpful to others in future also.
Hi,
You were close. In your game file you could have put a var _setgameSpeed and then from Intro you could adjust it by flashgame._setgameSpeed = gameSpeed; It's a bit more complicated though since you also have to setup a reference to flashgame in the first place. Let me explain...
Ideally you want to put all your code in one place (an .as file would be best but...) if you would rather use timeline then you should create a new empty layer called "actions" and put all your code in the first frame of that.
Also change your button to a movieClip type and remove any code within it since everything will be controlled by the code in "actions" layer. In the example I have that movieclip on the stage with instance name of "btn_load_SWF"
Intro.swf (Parent SWF file)
var my_Game_Swf:MovieClip; //reference name when accessing "flashgame.swf"
var _SWF_is_loaded:Boolean = false; //initial value
var set_gameSpeed:int; //temp value holder for speed
var swf_loader:Loader = new Loader();
btn_load_SWF.buttonMode = true; //instance name of movieclip used as "load" button
btn_load_SWF.addEventListener(MouseEvent.CLICK, load_Game_SWF);
function load_Game_SWF (event:MouseEvent) : void
{
//set_gameSpeed = 10 * numericStepper.value;
set_gameSpeed = 100; //manual set cos I dont have the above numericStepper
if ( _SWF_is_loaded == true)
{
stage.removeChild(swf_loader);
swf_loader.load ( new URLRequest ("flashgame.swf") );
}
else
{ swf_loader.load ( new URLRequest ("flashgame.swf") ); }
swf_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, Game_SWF_ready);
}
function Game_SWF_ready (evt:Event) : void
{
swf_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, Game_SWF_ready);
//Treat the Loader contents (flashgame.swf) as a MovieClip named "my_Game_Swf"
my_Game_Swf = swf_loader.content as MovieClip;
my_Game_Swf.gameSpeed = set_gameSpeed; //update gameSpeed variable in flashgame.swf
//also adjust SWF placement (.x and .y positions etc) here if necessary
stage.addChild(my_Game_Swf);
_SWF_is_loaded = true;
}
Now in you flashgame file make sure the there's also an actions layers and put in code like this below then compile it first before debugging the Intro/Parent file. When your Intro loads the flashgame.swf it should load an swf that already has the code below compiled.
flashgame.swf
var gameSpeed:int;
gameSpeed = 0; //initial value & will be changed by parent
addEventListener(Event.ADDED_TO_STAGE, onAdded_toStage);
function onAdded_toStage (e:Event):void
{
trace("trace gameSpeed is.." + String(gameSpeed)); //confirm speed in Debugger
//*** Example usage ***
var my_shape:Shape = new Shape();
my_shape.graphics.lineStyle(5, 0xFF0000, 5);
my_shape.graphics.moveTo(10, 50);
my_shape.graphics.lineTo(gameSpeed * 10, 50); //this line length is affected by gameSpeed as set in parent SWF
addChild(my_shape);
}
The key line in intro.swf is this: my_Game_Swf.gameSpeed = set_gameSpeed; as it updates a variable in flashgame.swf (referred as my_Game_Swf) with an amount that is taken from a variable in the Parent SWF.
This is just one way you can access information between two separate SWF files. Hope it helps out.

Saving textfield input

I'll explain a little before asking my question ... I've created numerous games which load and unload off a main menu.
The player enters their name on the main menu before playing any games and when the player completes a game I want to save their time (taken to complete the game) and unload this time back into the main menu.
Is there any way of saving the times using AS3 to a word document or something like this? I can't send the times to my website with php because the games will be used within a competition and it all needs to work with the internet.
Any ideas guys?
Edit:
var dataloader:URLLoader = new URLLoader();
var dataarray:Array = new Array(); // do this where you intialise other vars
function preparesave()
{
dataloader.load(new URLRequest("savedata.txt"));
}
dataloader.addEventListener(Event.COMPLETE,savedata);
function savedata (event:Event)
{
dataarray = event.target.data.split(/\n/);
dataarray.push(MyTimer);
var bytes:ByteArray = new ByteArray();
var fileRef:FileReference = new FileReference();
for (var i = 0; i < dataarray.length;i++)
{
bytes.writeMultiByte(dataarray[i] + "\n", "iso-8859-1");
bytes.writeMultiByte('English Game Time: ',"iso-8859-1");
bytes.writeMultiByte(HourText.text.toString(),"iso-8859-1");
bytes.writeMultiByte(':',"iso-8859-1");
bytes.writeMultiByte(MinuteText.text.toString(),"iso-8859-1");
bytes.writeMultiByte(':',"iso-8859-1");
bytes.writeMultiByte(SecondText.text.toString(),"iso-8859-1");
}
fileRef.save(bytes,"savedata.txt")
}
You could use a cookie(sharedObject) for this purpuse. See http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/SharedObject.html
var data:SharedObject = SharedObject.getLocal("userdata");
data.startTime = new Date().time;
If you need the startTime again you could just retrieve it by the cookie and variable name.
For small amounts of data, you're best-off just going with automaticoo's solution by using SharedObjects.. they take minimal time to set up and are an efficient way of storing small amounts of data.
However, if it's not for you, you could always load/save to a text file. You can do this using ByteArrays and FileReferences.
Since you brought up saving to a word file, I would suggest saving to a text file would be the best way of achieving your goal (although other than your word doc. suggestion, i'm not sure.. your aim is sort of unclear)
Here is a seriously quick demonstration of saving to a text file.. If you need help loading it too, let me know.
function savedata() {
var bytes:ByteArray = new ByteArray();
var fileRef:FileReference = new FileReference();
bytes.writeMultiByte(playername + "\n", "iso-8859-1");
bytes.writeMultiByte(playerscore.toString(),"iso-8859-1");
fileRef.save(bytes,"savedata.txt");
}
This is pretty simply.. By using writeMultiByte, we can write as much data as needed before saving our text file! This is especially useful if you have arrays of data you need to save.
Anyway, the "iso-8859-1" is simply a reference to the character set / file-format being used.. I'm not sure if you can simply write utf-16 etc. instead.. I've always just used it as it is written above.
The result in the text file here will be the following:
Peter
9547 (but up one line)
To load, you can just split data by line, resulting in an array full of strings and ints/numbers (however your scores may work). Again, let me know if you need help doing that.
I'm not sure if this is the most efficient method of achieving what you're after since your goal isn't entirely clear to me, but it has been a very useful way for myself in storing large amounts of data, which I'm guessing you are wanting to do if you are compounding all the scores of players.
edit:
Okay, to the questions you posed below:
To save more than one user's score is simple. Simply have a single array which loads the data from the text file (if the text file exists), then adds the new score to the end of the array, then saves back to the text file.
Here is an example:
var dataloader:URLLoader = new URLLoader();
var dataarray:Array = new Array(); // do this where you intialise other vars
function preparesave() {
dataloader.load(new URLRequest("savedata.txt"));
}
dataloader.addEventListener(Event.COMPLETE,savedata);
function savedata (event:Event) {
dataarray = event.target.data.split(/\n/);
dataarray.push(playername);
dataarray.push(playerscore);
var bytes:ByteArray = new ByteArray();
var fileRef:FileReference = new FileReference();
for (var i = 0; i < dataarray.length;i++) {
bytes.writeMultiByte(dataarray[i] + "\n", "iso-8859-1");
}
fileRef.save(bytes,"savedata.txt")
}
What this does is take any existing save data, pushes it to an array (where one line on your save file is one array data entry), adds your appropriate data, and pushes it back out to the save file.
(2) To load this in whilst in the main menu, simply place this code in the frame of the main menu..
dataloader.load(new URLRequest("savedata.txt"));
dataloader.addEventListener(Event.COMPLETE,loaddata);
function loaddata (event:Event) {
dataarray = event.target.data.split(/\n/);
}
This will load all your existing data into an array. What you do from then on is up to you.

ActionScript: How to Import XML data as a variable (not as an Event)

I am attempting to import some simple XML data into Flash ActionScript 3.0. I can easily do this as an import that is posted to the stage, but I want to save it as a global variable instead. Here is the XML file that I am pulling from:
<utilitySavings>
<nameof file="academicWaterSavings">
<waterValue>100</waterValue>
<elecValue>200</elecValue>
</nameof>
<nameof file="dormWaterSavings">
<waterValue>300</waterValue>
<elecValue>400</elecValue>
</nameof>
<nameof file="greekWaterSavings">
<waterValue>500</waterValue>
<elecValue>600</elecValue>
</nameof>
<nameof file="totalWaterSavings">
<waterValue>1500</waterValue>
<elecValue>1600</elecValue>
</nameof>
...and here is the actionscript:
var req:URLRequest = new URLRequest("data.xml");
var loader:URLLoader = new URLLoader();
var utilitySavings:XML;
function xmlLoaded(event:Event):void
{
utilitySavings = new XML(loader.data);
academicWater.text = utilitySavings.nameof[0].waterValue;
academicElec.text = utilitySavings.nameof[0].elecValue;
var dormWater:String = utilitySavings.nameof[1].waterValue;
trace (dormWater);
}
loader.addEventListener(Event.COMPLETE, xmlLoaded);
loader.load(req);
trace(academicWater.text);
Notice the 'trace (dormWater)' I want to trace this outside of the function so it is accessible in later in my script. I can trace within the function, but this does me no good. I also am able to get the dynamic text to show up on the stage but, likewise, this does me little good.
I appreciate any help or insights.
I can see a couple of ways of achieving this , if you want to create a globally accessible Object, create a Singleton( not recommended ) , load your XML data into it then every object in your app will be able to access the loaded XML data.
http://www.gskinner.com/blog/archives/2006/07/as3_singletons.html
The resulting code would give you something like this:
//Available throughout your app after the XML has been loaded & parsed
var dormWater:String = Singleton.dormWater;
Although you state you don't want Events, I think that using Signals could be a better approach. Load your XML and dispatch a Signal containing the relevant String to the object that needs it, when receiving the Signal , assign the String to a variable.
http://www.peterelst.com/blog/2010/01/22/as3-signals-the-best-thing-since-sliced-bread/
//In a specific class
private var _dormWater:String;
private function signalListener(value:Object ):void
{
_dormWater = value.dormWater;
}

flex: Create a screenshot of UI element

I want to make a screenshot of custom as3 ui element (which was extended from Canvas), and then upload the image on the server.
Could you help me with a small example of this?
I am trying to do the following:
// This is UI component extended from Canvas
var chessBoard:ChessBoard = new ChessBoard();
// I displayed pieces on the board, but didn't add it to the stage (I just need a
// a screenshot, not need them on the canvas)
chessBoard.displayPosition(DataStorage.getInstance().getStoredPosition(0));
var img:ImageSnapshot = ImageSnapshot.captureImage(chessBoard, 300, new PNGEncoder());
var obj:Object = new Object();
obj.complexity = complexity.value;
obj.img = img;
httpService.send(obj);
and getting this error:
ArgumentError: Error #2015: Invalid
BitmapData. at
flash.display::BitmapData() at
mx.graphics::ImageSnapshot$/captureBitmapData()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\graphics\ImageSnapshot.as:186]
at
mx.graphics::ImageSnapshot$/captureImage()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\graphics\ImageSnapshot.as:282]
at
ui::SendForm/send()[/Users/oleg/Documents/chess_problems/problemme/src/ui/SendForm.mxml:53]
at
> ui::SendForm/___SendForm_Button1_click()[/Users/oleg/Documents/chess_problems/problemme/src/ui/SendForm.mxml:16]
This error was caused by missing width and height of the Canvas. I set them and it helped to create bitmap data this way:
var bitmapData:BitmapData = new BitmapData(chessBoard.width,chessBoard.height);
var encoder:PNGEncoder = new PNGEncoder();
var data:ByteArray = encoder.encode(bitmapData);
I wonder how do I send the image to the server via httpService? Is there a way. Also is data = image file?
Here is a post on someone who has done this exact thing in AS3:
Dynamically Create an Image in Flash and Save it to the Desktop or Server
It is possible, and although I have never done it, this may be useful to you: http://www.flash-db.com/Tutorials/snapshot/