button to save as the video in the desktop - actionscript-3

I use Adobe Flash Professional CS6 + as3 and I have a button to download or save as the video in the desktop but does not execute it? Why ? Where is the mistake?
import fl.video.FLVPlayback;
import flash.display.StageAlign;
import flash.events.Event;
import flash.display.MovieClip;
import flash.display.StageScaleMode;
import flash.media.SoundMixer;
myVideoPlayer.source = "";
addChild (myVideoPlayer);
function loadMyVideo (url:String):void
{
myVideoPlayer.source = url;
myVideoPlayer.visible = true;
}
videosaveas.addEventListener (MouseEvent.CLICK, videosaveas2);
function videosaveas2 (e:Event):void
{
file = new FileReference();
var fileReference:FileReference=new FileReference();
file.save (ByteData, "video.mp4");
}

I don't know if you know the difference between a Flash Player app and an AIR one but I'll put an example for an offline Flash Player app to download a file which is in the same directory as the SWF.
To load the file, I'll use an URLLoader object and then save it using a FileReference one.
Here, don't forget that FileReference.save() is allowed only after a user action (like a mouse click or keypress).
For the example, I'll use the same button for both operations (the user should press the button twice to get the saving file dialog).
var url_loader:URLLoader;
// at the first, we use the button to load the file
btn_download.addEventListener(MouseEvent.CLICK, load_the_file);
function load_the_file(e:MouseEvent): void {
url_loader = new URLLoader();
url_loader.dataFormat = URLLoaderDataFormat.BINARY;
url_loader.addEventListener(Event.COMPLETE, function(e:Event){
btn_download.removeEventListener(MouseEvent.CLICK, load_the_file);
// then we use the same button to download the file
btn_download.addEventListener(MouseEvent.CLICK, download_the_file);
})
url_loader.load(new URLRequest('file_path.ext'));
}
function download_the_file(e:MouseEvent): void {
var file_reference:FileReference = new FileReference()
file_reference.save(url_loader.data, 'default_file_name.ext');
btn_download.removeEventListener(MouseEvent.CLICK, download_the_file);
}
Here, using one button is just an example so you can, for example, show a loading message, use another way to load the file, use two buttons, ...
Then for an online app (a web app), you can use, for example, FileReference.download() :
var file_ref:FileReference = new FileReference();
file_ref.download(new URLRequest('http://www.example.com/file_path.ext'));
For AIR, you have a lot of possibilities using the File, FileStream and the FileReference classes, and you have a lot of example on the net ...
Hope that can help.

Related

Adobe Flash: How to join several separate .swf files into one .exe file?

Noob ask:
I have many separate .swf files, they are like stairs..
for example:
menu.swf load scene1.swf
scene1.swf load scene2.swf
and so on...
There is a button in menu.swf to load scene1.swf and there is a button in scene1.swf to load scene2.swf and so on...
*every .swf file has it own code, I use Adobe Flash CS6 and Actionscript 3.0
I use loader to load those .swf file
var myLoader:Loader = new Loader();
var intro:URLRequest = new URLRequest("Intro.swf");
myLoader.load(intro);
addChild(myLoader);
My problem:
When I create project on menu.swf to menu.exe... press the button... it can't load any .swf file.. T-T"
so.. what should I do..?
here is sample of my project:
https://drive.google.com/folderview?id=0B7S5VF_EUl_dbEg1WmNCYVBfQTA&usp=sharing
*based on my project Little Red Riding Hood.swf is the main menu. It works fine when I run it with .swf
Edit:
This is my full code of the menu, perhaps anyone can help me out.. ^^
*this code works fine when I run it with .swf
btnRead.addEventListener(MouseEvent.CLICK, read);
btnPlay.addEventListener(MouseEvent.CLICK, read);
function read(event:MouseEvent):void {
var myScene1:Loader = new Loader();
var scene1:URLRequest = new URLRequest("scene1.swf");
myScene1.load(scene1);
addChild(myScene1);
}
btnAbout.addEventListener(MouseEvent.CLICK, about);
function about(event:MouseEvent):void {
gotoAndStop(4);
}
btnScene.addEventListener(MouseEvent.CLICK, scene);
btnScene1.addEventListener(MouseEvent.CLICK, scene);
function scene(event:MouseEvent):void {
gotoAndStop(5);
}
import flash.system.fscommand;
btnQuit.addEventListener(MouseEvent.MOUSE_DOWN, closeApp);
function closeApp(event:MouseEvent):void {
fscommand("quit");
}

Saving customized movieclip as an image to local disk (diy generator)

dropbox.com/s/77euop1luqjreos/FINAL.fla
Ok i just gave up with this already. I cant think of any way to save the image created by a user. Its hard to explain but please check out the fla file of my work. Basically its a diy generator. The only thing missing is a save function. Ive read filereference but its always in a document class. My code is in the timeline. Please help I'm really stuck.
edit: I got a download button that is working now!! But it only saves a small part of the movieclip: Imgur
In order to create images, you need to access the pixel data of the MovieClip object. The data can be obtained by rendering a MovieClip into a BitmapData object and using this data, you can write your own encoder to convert it to any image format you’d like. Writing such encoder is not a trivial task and requires understanding of the image format algorithm, or you can use pre-written libraries. You can download the PNGEncoder and JPGEncoder , which is part of as3corelib, an open source project library.
Using the JPGEncoder, we can convert DisplayObject into ByteArray, suitable for saving into file. If using the JPGEncoder, it’ll look like this:
import com.adobe.images.JPGEncoder;
var jpgEncoder:JPGEncoder = new JPGEncoder(quality);
//remember bitmapData here is just an example (do not try to compile this code without declare this particular variable)
var byteArray:ByteArray = jpgEncoder.encode(bitmapData);
With the PNGEncoder, it’ll look like this:
import com.adobe.images.PNGEncoder;
//remember bitmapData here is just an example (do not try to compile this code without declare this particular variable)
var byteArray:ByteArray = PNGEncoder.encode(bitmapData);
Saving Into User’s Hard Drive
Using the FileReference.save() function, we can prompt the user to save the file with the following call.
var fileReference:FileReference=new FileReference();
//in case of JPGEncoder
fileReference.save(byteArray, ".jpg");
With the two combined, here’s an example how to use:
//remember to import
import flash.net.FileReference;
import com.adobe.images.JPGEncoder; //or import com.adobe.images.PNGEncoder;
import flash.utils.ByteArray;
import flash.display.BitmapData;
//where mc_canvas will be your MovieClip instance name
var bitmapData:BitmapData = new BitmapData(mc_canvas.width, mc_canvas.height);
bitmapData.draw(mc_canvas);
var jpgEncoder:JPGEncoder = new JPGEncoder(quality_slider.value);
var byteArray:ByteArray = jpgEncoder.encode(bitmapData);
//if you want to use PNGEncoder
//var byteArray:ByteArray = PNGEncoder.encode(bitmapData);
var fileReference:FileReference = new FileReference();
fileReference.save(byteArray, ".jpg");

AS3 URLRequest Local File on multiple OS/Browsers

Greatings!
I have yet another question concerning the loading of a .swf inside a existing one.
In my game. I have a introduction screen in which I load another .swf (which is a movie).
This all works fine and the URLRequest is this:
request = new URLRequest("Movie.swf");
As I said, this works fine. However when I copy my game.swf and movie.swf to a USB stick.
(I put them in the same directory to prevent other issues).
It doesn't seem to find the movie.swf.
Now I know that it has to do with the path given in the URLRequest and/or the publish settings. But I do not know how to make this so that it searches in the same directory
as the game.swf is in.
I hope you guys have an answer for this issue.
Thanks in advance,
Matti.
Matti, I believe Lukasz's comment is correct about it being a security error.
You can avoid this security error by embedding Movie.swf instead of using a Loader. If you do this, then at compile-time the Movie.swf needs to sit next to the Game.as file, and it will be included in the Game.swf (no need to deliver both files, just Game.swf).
The syntax is:
package
{
import flash.display.Sprite;
public class Game extends Sprite
{
[Embed(source="MyMovie.swf")]
private var myMovieClass:Class;
private var myMovie:DisplayObject;
public function Game():void
{
myMovie = new myMovieClass();
// Technically myMovie is now a Loader, and once
// it's loaded, it'll have .content that's a
// MovieClipLoaderAsset, and .content.getChildAt(0)
// will be your MyMovie.swf main timeline.
}
}
}
Alternately, if you embed it as mimeType="application/octet-stream", you can get the bytes of the SWF and use it in your existing Loader's .loadBytes() method:
package
{
import flash.display.Sprite;
import flash.utils.ByteArray;
public class Game extends Sprite
{
[Embed(source="MyMovie.swf", mimeType="application/octet-stream")]
private var movieBytes:Class;
private var myMovie:DisplayObject;
public function Game():void
{
// Treat this loader the same as your current loader,
// but don't call .load(url), call loadbytes():
var l:Loader = new Loader();
l.loadBytes(new movieBytes() as ByteArray);
}
}
}

Yet another "local file access in actionscript-3" q-u-e-stion

I hope I can get some help with my actionscript problem.
(inb4: 'What exactly are you trying to accomplish (other than opening an arbitrary file without user permission)?' link)
I am trying to assist with student exercises - so I thought I'd come up with an example of a random gallery. The idea with this would be that students would be able to generate a SWF file, and in the same directory, they would have a folder with images. Then the SWF movie would read the contents of the directory; choose a random image, and display it.
I would have hoped that this could be done both locally (while students develop) - and, should they choose so, they should be able to upload the entire directory online -- and hopefully, the example would work either way. That turns out not to be so easy - so these are my questions:
They say, that in order to get local directory listing, I should use AIR - what does that mean? Is there some executable - other than flashplayerdebugger - that I should call in order to reproduce the SWF if it uses AIR?
Is it possible to get a local directory listing without using this AIR (in the similar vein as the Flex code below?)
It seems I can load a local text file; but I cannot load a local bitmap file. Would it be possible to load a bitmap file as well?
How can you give local access permission to files/folders, if it so happens that you don't have access to the Internet, so you cannot access settings_manager04.html - but you'd like to use a Flash application both with local files and with network sockets on the local network?
Now, one thing is that most students work with Flash CSx versions - I on the other hand am on Linux, so I have tried to make a Flex example; so I've provided the example as Flex code, but I'd like to know possible answers for the Flash CS environment too. The directory structure, compile lines, and code is given at end of this post - but here is how the "application" directory looks like:
Ok, so here is the problem in a bit more detail. First, I thought I'd try to read the directory contents - so I tried the code here: AS3 Basics: List all files in a folder including subdirectories (AIR ... on students' Flash CS - but that seemed to fail miserably.
So I thought - OK, then let's put in a text file in the same directory as the .swf, which will contain a list of the images; e.g.
cat > fileslist.txt <<EOF
img/01.jpg
img/02.jpg
EOF
Then, the Flash app would read this file first - and then proceed to choose a random image from the contents. But at the very first instant, I get:
An ActionScript error has occurred:
SecurityError: Error #2148: SWF file file:///home/rgaltest/rgaltest.swf cannot access local resource file:///home/rgaltest/fileslist.txt. Only local-with-filesystem and trusted local SWF files may access local resources.
at flash.net::URLStream/load()
at flash.net::URLLoader/load()
at rgaltest()[/home/rgaltest/rgaltest.as:23]
So, the answer to this seems to be:
"If you are getting that error when using flash.net.URLLoader and the free flex compiler, add the following option when you compile to get your swf to work: -use-network=false" (juicy tidbits - Only local-with-filesystem and trusted local SWF files may access local resources.)
"Turns out the solution is to configure your Flash Player to trust the swfs in the project’s /bin-debug directory ... 1) Goto http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html ... " (Solution – Error #2010: Local-with-filesystem SWF files are not permitted to use sockets. » Mark Lapasa)
Now, I would not like to have -use-network=false - because students may need to integrate other network based stuff in that example. Then again, something similar to that "settings_manager04.html" ("Global Security Settings panel") page shows up if you open the SWF in a browser, then right-click, then choose "Global Settings" - but does it work for SWF files being shown as a part of Ctrl-Enter build in Flash CS (or correspondingly, those that are open with flashplayerdebugger?) So I try it - choose "Edit Locations", "Browse for folder", choose /home/rgaltest under "Always Allow":
... and now the fileslist.txt gets loaded alright; also when the .swf is ran with flashplayerdebugger.
Right, so now that the files list is loaded, I'd proceed on loading the bitmaps.. so I add the respective code (with onImgLoaded etc), and this is what I get in the log:
At frame #1
file onTextLoaded: img/01.jpg,img/02.jpg,
At frame #2
file onImgLoaded: [object URLLoader]
TypeError: Error #1034: Type Coercion failed: cannot convert "ÿØÿà
...
¿ÿÙ" to flash.display.Bitmap.
at rgaltest/onImgLoaded()[/home/rgaltest/rgaltest.as:64]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
At frame #3
At frame #4
...
Interestingly - the image did get read - as all of its binary contents are dumped to the log! Yet, it cannot be interpreted as bitmap data???!
First of all, this is my directory layout:
mkdir /home/rgaltest
cd /home/rgaltest
touch rgaltest.as
touch fileslist.txt
mkdir img
cd img
convert -size 320x240 gradient:\#4b4-\#bfb 01.jpg
convert -size 320x240 gradient:\#b44-\#bff 02.jpg
chmod -R 777 /home/rgaltest # to ensure no problem with file permissions
The rgaltest.as is given below; I compile that with:
/path/to/flex_sdk_4.6.0.23201_mpl/bin/mxmlc -static-link-runtime-shared-libraries -use-network=true -verbose-stacktraces -debug=true rgaltest.as
... and I check that locally with (make sure mm.cfg is properly set up, see also Using Flash Player debugger):
# in one terminal:
tail -f ~/.macromedia/Flash_Player/Logs/flashlog.txt
# in another terminal:
/path/to/flashplayer_11/flashplayerdebugger rgaltest.swf
And finally, here is rgaltest.as:
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.net.*; //URLLoader;
import flash.display.Bitmap;
import flash.display.BitmapData;
[SWF(width="550", height="400")]
public class rgaltest extends MovieClip {
public var _pictureArray:Array;
public var frameCnt:Number = 0;
public var myTextLoader:URLLoader;
public var isFileslistLoaded:Boolean = false;
public var myImgLoader:URLLoader;
public var isImgLoading:Boolean = false;
// constructor - create/initialize objects here
public function rgaltest() {
this.stage.frameRate = 10; // frames per second
// load the text file with image list
myTextLoader = new URLLoader();
myTextLoader.addEventListener(Event.COMPLETE, onTextLoaded);
myTextLoader.load(new URLRequest("fileslist.txt"));
// add event listener for onEnterFrame
configureListeners(this);
}
private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.ENTER_FRAME, my_OnEnterFrame);
}
public function onTextLoaded(e:Event):void {
_pictureArray = e.target.data.split(/\n/);
trace("file onTextLoaded: " + _pictureArray);
isFileslistLoaded = true;
}
public function my_OnEnterFrame(event:Event):void {
frameCnt++;
trace("At frame #" + frameCnt);
if (isFileslistLoaded) {
if (!isImgLoading) {
//load a random image
var rndChoice:Number = Math.floor(Math.random()*2) + 1;
myImgLoader = new URLLoader();
myImgLoader.addEventListener(Event.COMPLETE, onImgLoaded);
myImgLoader.load(new URLRequest(_pictureArray[rndChoice]));
isImgLoading = true;
}
}
} // end onEnterFrame
public function onImgLoaded(e:Event):void {
trace("file onImgLoaded: " + e.target);
var _image:Bitmap = Bitmap(e.target.data);
var _bitmap:BitmapData = _image.bitmapData;
addChild(_image);
}
} //end class
} //end package
Some other relevant links:
flex - Adding Local Filenames/References To Array In Actionscript - Stack Overflow
flash - Is there a way to read local files in ActionScript 3 "silently"'? - Stack Overflow
adobe flash cs4 as3: get current directory of a running project? - Stack Overflow
flex - open local files in AS3 - Stack Overflow
Bump - it seems I solved the bitmap loading (putting it here in separate post, so that I don't clog the OP too much); I just used Loader class instead of URLLoader; see code below (also note the mistake in random calculation in OP, which is corrected below).
Anyways - this is the thing: when I tried the Loader class on the students' Flash CSx, it tended to fail miserably! But, maybe that was because in those cases, we didn't give any permissions to the folder from "settings_manager04.html"? Any special things that should be taken care of, when a code similar to this is generated in Flash?
Here is the reworked rgaltest.as:
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.net.*; //URLLoader;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader; //*
[SWF(width="550", height="400")]
public class rgaltest extends MovieClip {
public var _pictureArray:Array;
public var frameCnt:Number = 0;
public var myTextLoader:URLLoader;
public var isFileslistLoaded:Boolean = false;
public var myImgLoader:Loader;
public var isImgLoading:Boolean = false;
// constructor - create/initialize objects here
public function rgaltest() {
this.stage.frameRate = 10; // frames per second
// load the text file with image list
myTextLoader = new URLLoader();
myTextLoader.addEventListener(Event.COMPLETE, onTextLoaded);
myTextLoader.load(new URLRequest("fileslist.txt"));
// add event listener for onEnterFrame
configureListeners(this);
}
private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.ENTER_FRAME, my_OnEnterFrame);
}
public function onTextLoaded(e:Event):void {
_pictureArray = e.target.data.split(/\n/);
trace("file onTextLoaded: " + _pictureArray);
isFileslistLoaded = true;
}
public function my_OnEnterFrame(event:Event):void {
frameCnt++;
trace("At frame #" + frameCnt);
if (isFileslistLoaded) {
if (!isImgLoading) {
//load a random image
var rndChoice:Number = Math.floor(Math.random()*2) + 0;
trace("Loading: " + rndChoice + " / " + _pictureArray[rndChoice]);
myImgLoader = new Loader();
myImgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImgLoaded);
myImgLoader.load(new URLRequest(_pictureArray[rndChoice]));
isImgLoading = true;
}
}
} // end onEnterFrame
public function onImgLoaded(e:Event):void {
trace("file onImgLoaded: " + e.target);
var _image:Bitmap = Bitmap(myImgLoader.content);
var _bitmap:BitmapData = _image.bitmapData;
addChild(_image);
}
} //end class
} //end package

Saving XML file in AS3 is possible

var xml:XML = <myXml>
<item prop="1" />
<item prop="2" />
</myXml>;
I need to save as xml file in local harddisk(project directory).
Is it possible to save in as3 itself?
I threw this together, and sure enough you can save to .XML using the following as a minimalist example.
package com.hodgedev.xmlcreator
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.utils.ByteArray;
import flash.net.FileReference;
/**
* ...
* #author Brian Hodge (brian#hodgedev.com)
*/
public class Main extends Sprite
{
private var _xml:XML;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
//Calling the save method requires user interaction and Flash Player 10
stage.addEventListener(MouseEvent.MOUSE_DOWN, _onMouseDown);
_xml= <xml>
<test>data</test>
</xml>;
}
private function _onMouseDown(e:MouseEvent):void
{
var ba:ByteArray = new ByteArray();
ba.writeUTFBytes(_xml);
//ba.
var fr:FileReference = new FileReference();
fr.addEventListener(Event.SELECT, _onRefSelect);
fr.addEventListener(Event.CANCEL, _onRefCancel);
fr.save(ba, "filename.xml");
}
private function _onRefSelect(e:Event):void
{
trace('select');
}
private function _onRefCancel(e:Event):void
{
trace('cancel');
}
}
}
There are some things to note.
You require Flash Player 10 to use the save method of the FileReference class.
In order to do anything that INVOKES a prompt, Flash requires user interaction like keyboard or mouse input.
In the above I listen for MouseEvent.MOUSE_DOWN on the stage to serve as the USER INTERACTION which is required to invoke the save prompt.
I setup a basic XML structure within the code (this will typically come from and external source and will work fine both ways.
A ByteArray is created and the XML is written to the ByteArray.
The save method of the FileReference class requires a ByteArray and default save name be passed as the two parameters.
I hope this helps.
if you want to store it locally (on the client PC) , you can use a local shared object. Refer to this tutorial
I'm sorry, your question isn't very clear.
Are you asking if you can save a file to the hard drive from within a compile SWF written in AS3?
Or are you asking if you can include a raw XML file in your AS3 project without needing to write it out as a variable?
If you meant the former, no -- not without Adobe AIR. You can save data locally as a SharedObject, but not as an arbitrary file in the file system.
If the latter, then yes -- you must embed the file just as you would embed another resource (such as an image or a sound). However, it looks like there might be a bug in Flash that makes this non-trivial to figure out how to do.
This link might be of help to you.
[Embed(source='../../../../assets/levels/test.xml', mimeType="application/octet-stream")]
public static const Level_Test:Class;
And then to parse the XML:
var ba:ByteArray = (new Levels.Level_Test()) as ByteArray;
var s:String = ba.readUTFBytes( ba.length );
xml = new XML( s );
Apologies if neither of those questions are what you were actually asking.
Cheers!