I have problem in creating swf file runtime from an adobe air application. For example I create animation using https://github.com/jamesflorentino/Flip-Planes-AS3, I have converted the Sprite extension to MovieClip, the animation runs very good. Now I would like to make the animation could be save as swf file by user.
I have tried as3swf with script like this:
private function createSwf():void{
//let make example the Main class is taken from github above
var _main:Main = new Main();
// in this case i use AS3SWF plugin
var _swf:SWF = new SWF(_main.loaderInfo.bytes);
// this is for copy byteArray from the _swf convertor
var buffer:ByteArray = new ByteArray();
_swf.publish(buffer);
saveToDesktop(buffer);
}
private function saveToDesktop(_ba:ByteArray):void{
// create the file on the desktop
var myFile:File = File.desktopDirectory.resolvePath("demo.swf");
// create a FileStream to write the file
var fs:FileStream = new FileStream();
// add a listener so you know when its finished saving
fs.addEventListener(Event.CLOSE, fileWritten);
// open the file
fs.openAsync(myFile, FileMode.WRITE);
// write the bytearray to it
fs.writeBytes(_ba);
// close the file
fs.close();
}
private function fileWritten(e:Event):void{
trace("new swf file is created");
}
After all those process i got generated swf in my desktop folder with name demo.swf but when i open the file, it is only a white background with error message:
VerifyError: Error #1014: Class flash.events::NativeWindowBoundsEvent could not be found.
at flash.display::MovieClip/nextFrame()
at mx.managers::SystemManager/deferredNextFrame()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\SystemManager.as:278]
at mx.managers::SystemManager/preloader_preloaderDocFrameReadyHandler()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\SystemManager.as:2627]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.preloaders::Preloader/timerHandler()[E:\dev\4.y\frameworks\projects\framework\src\mx\preloaders\Preloader.as:515]
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
please help me what is the best way to create swf file runtime, both from script side or command line side as long as not server side because it is desktop application.
Many Thanks
Creating a SWF at runtime is not going to be the same as taking an in memory byte array representation of an animation and saving it with a SWF extension.
If you want to build a SWF from AIR; you may consider bundling the Flex Framework with your application and use a NativeProcess to trigger mxmlc to generate a SWF. You'll need source code [or SWCs] to do this, though, it won't work with already compiled assets/classes from your running application.
Or you may want to review the file format for a SWF and go about creating it manually from your AIR application. I have no doubt this is possible, but I do not expect it to be trivial.
Related
I need to read a part of two files, and once both parts of both files are loaded to trigger a function that does some work.
What is the best way to approach this problem.
I am currently triggering the second file load once the first is loaded, however it seems poor coding style, I think this because my OO code starts looking procedural.
EDIT: So its an Air based app so using filestream.
In the end I found I actually needed to read each file in a different way. Because I need the same part of both files, and I dont know the file size, I need to read one file first and once I have fileStream.bytesAvailable and position, I can then look for the same data from the second file. I found I must handle files smaller than my read size and the end of files beyond multiples of my read size.
You don't specified what file and from where you wont to load the file but you can actually load multiples files in parallel.
If you want to read only part of file from local machine you can use AIR's FileStream class - very easy and you don't have to load whole few hundreds MB file:
import flash.filesystem.*;
var file:File = File.documentsDirectory;
file = file.resolvePath("Apollo Test/test.txt");
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var str:String = fileStream.readMultiByte(file.size, File.systemCharset);
trace(str);
fileStream.close();
Another option is to use URLStream and listen for ProgressEvent.PROGRESSevents to read data of partially loaded file.
You may also want to see NetStream class which is used to stream video.
there is many options, using File, FileStream is only available on air applications.
The File class extends the FileReference class. The FileReference
class, which is available in Flash® Player as well as Adobe® AIR®,
represents a pointer to a file, but the File class adds properties and
methods that are not exposed in Flash Player (in a SWF running in a
browser), due to security considerations.
as noted above, if you are creating a non-AIR application, FileReference should be used instead of FileStream and File classes, as you dont tagged AIR in your question.
FileReference does not provide any open("path") to you (due to security considerations), but a browse method will be available and ask's your client's for selecting a file. here is an example, which also explain how to trigger a function when opening is done:
var filereference:FileReference = new FileReference();
filereference.addEventListener(Event.SELECT, onFileSelected);
var text_files:FileFilter = new FileFilter("Text Files","*.txt; *.html;*.htm;*.php");
var all_files:FileFilter = new FileFilter("All Files (*.*)","*.*");
filereference.browse([text_files, all_files]);
// triggered when a file is selected by user
function onFileSelected(e:Event):void {
filereference.removeEventListener(Event.SELECT, onFileSelected);
filereference.addEventListener(Event.COMPLETE, onFileLoaded);
filereference.load();
}
// triggered when file loading is complete
function onFileSelected(e:Event):void {
var data:ByteArray = fileReference["data"];
filereference.removeEventListener(Event.COMPLETE, onFileSelected);
}
two more events to be listened for suddenly error's occurred and displaying a progress bar for loading progress (its sync):
IOErrorEvent.IO_ERROR and ProgressEvent.PROGRESS
What i have
Large amount of swfs without it's sources (so i couldn't modify its)
What i need
To load and play this swfs with my AIR app.
The problem
The problem is that this swfs seems having
Security.allowDomain('*')
in their source, so they would throw
SecurityError: Error #3207: Application-sandbox content cannot access
this feature.
after i load it. I know that Air doesn't need to use this line, but instead of ignoring or warning on it my full app would stop to executing after loading one of this swfs. If only i could try/catch this string, but as i said i don't have an source of that swfs, so the only thing i could do is to modify my AIR app.
What i tried
What i already tried is to catch all errors inside loader by doning
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loaderIOErrorHandler);
private function loaderIOErrorHandler(e:IOErrorEvent):void {
e.preventDefault();
}
but it seems it isn't catch errors inside loader at all
Update
I couldn't share one of this swfs, but here is simulation i made that reproduce problem https://www.dropbox.com/s/0spbdzijfpboi47/problematicSwf.swf?dl=0
Here it's init code
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
Security.allowDomain('*');
tf = new TextField();
tf.text = 'Me loaded!';
addChild(tf);
}
As you could see it is crashing on allowDomain inside loaded swf.
And here is how i load it
var ctx:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
loader.load(new URLRequest(path), ctx);
This is a typical security restriction but it's a very strict one and it's purpose is to make sure the served swf will never be used outside of what it was made for in the first place.
So the short answer to your problem is this: externally loaded swf that are sandboxed with "Security.allowDomain('*');" will not allow a sandboxed AIR app to interact with them in anyway. Instead those swf will be able to interact with the parent AIR app under restrictions via a sandbox bridge.
If truly you cannot modify those swf then you will never be able to add them to a display list in a AIR app or call any of their methods. A sandbox bridge will also be of no use to you.
It's not the answer you want to hear I bet but it's the only one you'll get.
I have a Flash / Actionscript 3 based desktop app wrapped in an *.exe using Zinc 4.0. I am using Flash Pro CS5.
I need to start saving very large image files locally. I have messed around with JPG Encoding these images before saving them to a local file via Zinc. I solved the actionscirpt timeout issue using This "asyncronous like" method. Encoding a 1.5 MP image takes about 5 seconds which is alright, but encoding an 8 MP image file takes about 40 seconds, which is not acceptable.
One idea I had is to save the BitmapData locally to a temporary Bitmap file (*.bmp), without having the end user to wait for JPG Encoding in Flash, and then use my already existing image processor (written in C#) to read the bitmap file and encode it without waiting on Flash to do it, effectively offloading the task away from the user.
I have used BitmapData.getPixels() to try and write the byte array directly to the file, using the same Zinc method as I do successfully with encoded JPGs, but the *.bmp file is unreadable. Are there some file headers that would need to be included in addition to the BitmapData getPixel()'s byte array to successfully save a bitmap image? If so how could I successfully add them to the byte array before writing to file?
Any guidance, clarification or other solutions much appreciated.
I've found a solution for my needs, and just in case others have similar needs:
To save an actual Bitmap (*.bmp) file, Engineer's suggested Btimap encoder class was awesome. Very fast on the actual encoding; however, since my file writing call in Zinc is synchronous and bitmap files are a lot larger than JPGs it really just moved my bottle neck from encoding to the file saving, so I decided to look elsewhere. If Zinc had an asynchronous binary file writing method that would not lock up the GUI I would have been happy, but until then this is not the solution for me.
I stumbled across a Flash Alchemy solution, with great results. Instead of waitint abour 40 seconds to encode an 8 MP image, it now only takes a few seconds. This is what I did:
Downloaded the jpegencoder.swc from this page and saved it in my project directory
Added the swc: Publish Settings > Flash (tab) > Script: Actionscript 3.0 "Settings..." button > Library path (tab)> and added that .swc with Link Type = "Merged into code"
Then used it :
(below is my modified code with just the basics)
import flash.utils.ByteArray;
import flash.display.BitmapData;
import cmodule.aircall.CLibInit; //Important: This namespace changed from previous versions
var byteArrayResults:ByteArray; //Holds the encoded byte array results
public static function startEncoding(bitmapData:BitmapData):void {
var jpeginit:CLibInit = new CLibInit(); // get library
var jpeglib:Object = jpeginit.init(); // initialize library exported class to an object
var imageBA:ByteArray = bitmapData.getPixels(bitmapData.rect); //Getpixels of bitmapData
byteArrayResults = new ByteArray();
imageBA.position = 0;
jpeglib.encodeAsync(encodeComplete, imageBA, byteArrayResults, bitmapData.width, bitmapData.height, 80);
}
private static function encodeComplete(thing:*):void
{
// Do stuff with byteArrayResults
}
You may find this link useful as well:
http://last.instinct.se/graphics-and-effects/using-the-fast-asynchronous-alchemy-jpeg-encoder-in-flash/640
my answer is late but maby it helps.
i developed a AIR mobile app to save imgs from the device camera on the device and upload it to the server.
since air 3.3 you have this bitmapdata encode functionality:
var ba:ByteArray = new ByteArray();
var bd:BitmapData = new BitmapData(_lastCameraPhotoTmpBmp.width, _lastCameraPhotoTmpBmp.height);
bd.draw(_lastCameraPhotoTmpBmp);
bd.encode(new Rectangle(0, 0, 1024, 768), new JPEGEncoderOptions(80), ba);
var localFile:File = File.applicationStorageDirectory.resolvePath("bild.jpg");
var fileAccess:FileStream = new FileStream();
fileAccess.open(localFile, FileMode.WRITE);
fileAccess.writeBytes(ba, 0, ba.length);
fileAccess.close();
the encode to jpg takes ~100ms on mobile devices in my tests.
greetings stefan
I want to send data generated by a flash module into an external executable in windows. From what I've learnt about interprocess communication, I think it is appropriate to use pipes in this case. I am using Flash professional CS5 and when a 'trace' command is used in actionscript the ouput will be displayed in the output window in flash professional. I think Flash pipes the data into the output window and if so is it possible to obtain the handle to that pipe. Is there a way by which I can write the output from flash player itself when the trace commands are executed or the data generated on an event directly into the buffer of a pipe.
Please help me out.
Thanks in advance.
I did some tricks using a Flash Badge, AIR app. and C# console app..
We can send params to an AIR app. from BADGE and receive it using:
protected function onInit(event:FlexEvent):void{
NativeApplication.nativeApplication.addEventListener(BrowserInvokeEvent.BROWSER_INVOKE, onBrowserInvoke);}
protected function onBrowserInvoke(e:BrowserInvokeEvent):void{
//reading args
var a:String = e.arguments[0];
//Now we can run *.exe from windows using:
if(NativeProcess.isSupported)
{
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
nativeProcessStartupInfo.executable = File.applicationDirectory.resolvePath("ExecutableApp.exe");
nativeProcessStartupInfo.arguments.push(a);
var process:NativeProcess = new NativeProcess();
//dispatched when the process will be finished
process.addEventListener(NativeProcessExitEvent.EXIT,onProcessDone);
//run
process.start(nativeProcessStartupInfo);
}
else Alert.show("Native process are not supported\nPrinter settings may be wrong!");
}
It's a long way, but certainly works! At least for me it worked.
I'm loading as2 swf into AIR application. It works properly when loaded from file. But when loaded from bytes, it is broken in some way (it reacts to mouse, but some elements are inactive)
var bytes:ByteArray = ... //loaded from resources
var loader:Loader = new Loader();
var context:LoaderContext = new LoaderContext(false);
context.allowCodeImport = true; //this is neccessary
// Method 1 - blocks some scripts in loaded SWF
//context.applicationDomain = new ApplicationDomain();
// (application domain has no effect with as2 swf)
//context.securityDomain = SecurityDomain.currentDomain; //gives error 2114: securityDomain must be null
loader.loadBytes(bytes, context);
// Method 2 - loads properly
//loader.load(new URLRequest(file.url));
So why not just load it from file? My resources are protected with encryption and I can't dump them to disk - they must still be protected.
What tricks may exist to load from bytes properly?
There is similar question, but in my case as2 causes more problems.
AS2 and AS3 use different runtimes (bytecode is different) so you won't be able to properly execute any AS2 bytecode in the AS3 runtime. you are basically injecting AS2 code into your AS3 application, so it ain't gonna work :/
According the the documentation for LoaderContext you should only use the applicationDomain property only when loading ActionScript 3.0 SWFs. Try dropping that parameter (or setting it to null) and see what happens.
It seems that old SWF movies (AS1 and AS2, which require AVM1) loaded into an AIR app with load get put in their own domains, but those loaded with loadBytes share a domain. So if you have multiple AVM1 SWFs loaded with loadBytes their _global properties will clobber each other. This affects the Flash MX UI components (ca. 2002).
I can't be the only one trying to package ancient Flash files in AIR apps, so I figure this info may be useful to someone.