Save and Load current frame in Actionscript 3 (Adobe Flash AIR) - actionscript-3

I have an interactive flash application Actionscript 3 to be deployed in Android device (thru Adobe Air). There will be a Save button (btnSave) that will save current progress of a user eventhough he closes the app or another will use it. There's also a Load button (btnLoad) to load the progress of the user. This is my code and I can't make it work. Thanks!
var mySharedObject:SharedObject = SharedObject.getLocal(“save”);
btnSave.addEventListener(MouseEvent.CLICK, saveCurrentFrame);
function saveCurrentFrame(event:MouseEvent):void
{
mySharedObject.data.lastframe= this.currentFrame;
mySharedObject.flush();
}
btnLoad.addEventListener(MouseEvent.CLICK, getLastFrame);
function getLastFrame():int
{
return mySharedObject.data.lastframe;
}

You need not only to read the saved last frame, but to move the playhead to it as well.
var mySharedObject:SharedObject = SharedObject.getLocal("save");
btnSave.addEventListener(MouseEvent.CLICK, saveCurrentFrame);
btnLoad.addEventListener(MouseEvent.CLICK, getLastFrame);
function saveCurrentFrame(event:MouseEvent):void
{
mySharedObject.data.lastframe = currentFrame;
mySharedObject.flush();
}
function getLastFrame(event:MouseEvent):void
{
if (mySharedObject.data.lastframe != null)
{
gotoAndStop(mySharedObject.data.lastframe);
}
}

Related

create js as3 flash canvas js frame code runs once

The js code generated in the files output in Adobe Animation for HTML5 Canvas contains an object for the movie clip that include the code that is to be run in each frame.
(lib.cdseacc02_07 = function(mode,startPosition,loop) {
// timeline functions:
this.frame_0 = function() {
if(typeof showNarration !== "undefined"){ showNarration(1); }
}
this.frame_644 = function() {
playSound("02_07_01wav");
}
this.frame_652 = function() {
this.closeBtn_1.addEventListener("click", closepopup_1.bind(this));
}
this.frame_738 = function() {
this.stop();
}
}).prototype = p = new cjs.MovieClip();
If gotoAndPlay is called on the movieclip from this code the code on the frame function is not run on the frames as they are passing by, this frame code only works the first time the timeline is played. Is there any way to make it so that the code on the frames can run each time the playhead passes that frame even if it was through a gotoAndPlay call in the code?
Frame actions should absolutely be played each time the timeline passes that frame, whether during gotoAndPlay or gotoAndStop. In fact, this sometimes causes issues where things event listeners are added multiple times (each time the framehead passes the script, like on your frame 652).
Can you post a simplified example of this not working?

AS3 Preloader doesn't work locally, loaderInfo ProgressEvent.PROGRESS event does not fire

Making a custom AS3 preloader, I noticed that when my SWF is executed locally (file:///) the preloader gets stuck in the loading screen when previewed in a web browser like Chrome.
When executed from a remote server or through the standalone Flash Player, then it works. I noticed other SWF that have preloaders do not have this issue. What I need to change?
this.loaderInfo.addEventListener(ProgressEvent.PROGRESS, preloaderProgress);
function preloaderProgress(event:ProgressEvent):void {
var loadedPercent:Number = event.bytesLoaded/event.bytesTotal*100;
if (loadedPercent == 100){
this.gotoAndStop(2);
}
}
Loading locally goes very fast. Not only you should check if the file is completely loaded using the Event.COMPLETE and not the ProgessEvent but you should also make sure to register your listeners before actually calling load or the file might end up completely loaded before you register your listeners.
Following the example at http://stephenscholtz.com/201110/single-movie-flash-preloading-as3
It seems that there was no ProgressEvent.COMPLETE, but there is a Event.COMPLETE instead, a bit confusing.
I changed my code to the following, (also including some tweaks for right click menu to prohibit the user from right clicking and pressing Play before movie has loaded and such)
//Initialize any variables
var loadedPercent:Number = 0;
//Remove all items from right click Flash Player menu (except Quality, and the mandatory About... & Settings...)
var cxMenu:ContextMenu = new ContextMenu();
cxMenu.hideBuiltInItems();
cxMenu.builtInItems.quality = true;
this.contextMenu = cxMenu;
/* or disable right click menu completely (Flash Player 11.2.202.228 and over) */
/* this.addEventListener(MouseEvent.RIGHT_CLICK, onMouseRightClick);
function onMouseRightClick(event:MouseEvent)
{
return false;
} */
//Disable shortcut keys and window menubar when played from desktop Standalone Flash Player app
if (Capabilities.playerType == "StandAlone" || Capabilities.playerType == "External") {
fscommand("showmenu", "false");
fscommand("trapallkeys", "true");
}
/* Preloader: begin */
//Update loading bar and percent text as SWF loads
function onProgress(e:Event) {
//Get the amount of bytes that have been loaded / bytes total to load
loadedPercent = this.loaderInfo.bytesLoaded/this.loaderInfo.bytesTotal*100;
//Update the text of _preloaderProgress movieclip
_preloaderProgress.text = int(loadedPercent)+"%";
//Update the _preloaderBar amount by scaling horizontally as it loads
_preloaderBar.scaleX = loadedPercent/100;
}
//Go to next frame after everything loads
function init(e:Event) {
gotoAndStop(2);
}
//Attach the events to the stage
this.loaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
this.loaderInfo.addEventListener(Event.COMPLETE, init);
/* Preloader: end */
//Stop to 1st frame and wait until it is loaded
stop();
This will allow the movie to play both remotely and locally with no problems.

How to make a close button for a Flash banner ad with Actionscript 3

I am working on a Flash banner ad built with Actionscript 3. It will be embedded into web pages.
The ad needs to have a close button. When the user clicks the button the ad should disappear.
This needs to be done entirely in the banner, as we have no control over the webpages where it will be embedded.
In Actionscript 2 I used to do this by running this code when the user clicked the button:
unloadMovie(this);
This seems to no longer work in Actionscript 3. What can I do to achieve this functionality in AS3?
Thanks for your help.
For documentation purposes, here are the conclusions Andreyu and I reached regarding the issue: unloading/removing a swf file from within the swf to allow users access to the elements under the swf.
One option is to use ExternalInterface to inject js code to:
get the id/name of the swf as registered with the DOM
remove the swf element from the DOM using the found id/name
In terms of code, this is using a technique described on Zeh Fernando's blog
as modified by Andreyu to include the DOM element removal:
// Based on work by Zeh Fernando: http://zehfernando.com/2011/getting-the-swfs-html-objectembed-id-from-within-the-flash-movie-itself/
function getSWFObjectName(): String {
// Returns the SWF's object name for getElementById
// Based on https://github.com/millermedeiros/Hasher_AS3_helper/blob/master/dev/src/org/osflash/hasher/Hasher.as
var js:XML;
js = <script><![CDATA[
function(__randomFunction) {
var check = function(objects){
for (var i = 0; i < objects.length; i++){
if (typeof(eval("objects["+i+"]." + __randomFunction)) != undefined) {
return objects[i].id;
}
}
return undefined;
};
return check(document.getElementsByTagName("object")) || check(document.getElementsByTagName("embed"));
}
]]></script>;
var __randomFunction:String = "checkFunction_" + Math.floor(Math.random() * 99999); // Something random just so it's safer
ExternalInterface.addCallback(__randomFunction, getSWFObjectName); // The second parameter can be anything, just passing a function that exists
return ExternalInterface.call(js, __randomFunction);
}
// Function to remove the SWF from the webpage
function destroyEverything(event:MouseEvent): void {
var js:XML;
js = <script><![CDATA[
function(__SWFContext) {
var element = document.getElementById(__SWFContext);
element.parentNode.removeChild(element);
}
]]></script>;
ExternalInterface.call(js, getSWFObjectName());
}
// Add function to click event of button
close_button.addEventListener(MouseEvent.CLICK, destroyEverything);
If unloadMovie was enough for you, you could simply remove everything from the stage:
//In button click handler, call "removeEverything" function
//function onClickClose(e:MouseEvent):void{
// removeEverything()
//}
//As a result you will get empty stage
function removeEverything():void {
while (stage.numChildren) {
stage.removeChildAt(0);
}
}

AS3 navigateToURL only works when testing in Flash CC

I've tried searching stackoverflow to find an answer to this question but so far haven't found anything.
I have a swf file with several movie clips on the stage. When I've managed to create an event where the movie clips swap out to a new movie clip when the user hovers. The problem that I am having is when you click that new movie clip it's supposed to open a URL in a browser window. That happens when I test the movie within Flash CC but when I test it in a browser nothing happens.
Any help for this would be greatly appreciated. I apologize if this question has been asked elsewhere on the site but, as I said, I did a search earlier and didn't find anything.
import flash.events.MouseEvent;
addEventListener(MouseEvent.MOUSE_OUT, gobackAnimation);
function gobackAnimation(event:MouseEvent):void
{
MovieClip(parent).gotoAndStop(1)
}
addEventListener(MouseEvent.CLICK, openURL);
function openURL(event:MouseEvent):void
{
ExternalInterface.call("open", "URL I'm trying to open");
MovieClip(parent).gotoAndStop(1)
}
To open a URL you have to use the navigateToURL function as documented here.
It appears that you are using the following code to trigger a URL to open:
function openURL(event:MouseEvent):void
{
ExternalInterface.call("open", "URL I'm trying to open");
MovieClip(parent).gotoAndStop(1)
}
However, I don't know where or what this ExternalInterface is and how the call function is built.
If you want to open a URL though, you should be doing something along the following lines:
function openURL(event:MouseEvent):void
{
var myURL:String = "http://your.url.goes/here"; // set your url here
var window:String = "_blank"; // you can set this to be whatever you need based on how you want the window opened
var request:URLRequest = new URLRequest(myURL);
request.data = variables;
try {
navigateToURL(request,window);
}
catch (e:Error) {
// handle error here
}
MovieClip(parent).gotoAndStop(1)
}

AS3: Call function does not work in browser

Here I have AS3 to for uploading recorded sound file to server. When I test it in Flash it works properly (record sound and upload it and goes to next frame) , but in browser it doesn't work. It seems can't call myUpload but I don't why? Is it should be mouse event? Thanks.
function VOCWordToYourMp3()
{
setTimeout(startRecording,3000);
recorder.addEventListener(RecordingEvent.RECORDING, onRecording);
recorder.addEventListener(Event.COMPLETE, onRecordComplete);
}
function startRecording()
{
if (! recording)
{
recorder.record();
}
else if (recording)
{
recorder.stop();
recording = false;
}
}
function onRecording(e:RecordingEvent)
{
//
}
function onRecordComplete(e:Event):void
{
//
}
function renderWav(src, convertToMp3 = false)
{
//
function handleRenderTimer(e:TimerEvent)
{
//
}
function finishRender()
{
//
}
}
function makeIntoMp3(wav)
{
wav.position = 0;
mp3Encoder = new ShineMP3Encoder(wav);
mp3Encoder.addEventListener(Event.COMPLETE, mp3EncodeComplete);
mp3Encoder.addEventListener(ProgressEvent.PROGRESS, mp3EncodeProgress);
mp3Encoder.start();
function mp3EncodeProgress(e:ProgressEvent):void
{
//
}
function mp3EncodeComplete(e: Event):void
{
myUpload('sound1',mp3Encoder.mp3Data);
}
}
function myUpload(namefile:String,sba: ByteArray):void
{
//upload code
}
Update:
In Flash Player 10 and Actionscript 3.0, all the calls to URLLoader must be in the same callstack.
http://helpx.adobe.com/flash-player/kb/user-interaction-required-upload-download.html
What is same callstack mean?
I recommend using something like Vizzy: https://code.google.com/p/flash-tracer/ to debug your swf in the browser. You can put trace statements into the onRecordComplete() and myUpload() functions, etc, to see how far the code is getting, and to see if you are getting any new errors. You may have some kind of security sandbox error because you are running in the browser. Being able to see what that error is will help you figure out what to do next.
To use Vizzy, you need to have the debug player running in your browser, and to configure the right path to your log file. This is sometimes a little bit tricky, so I'll give you some tips:
Add a file to your home directory called mm.cfg, and populate it with these settings:
ErrorReportingEnable=1
AS3Verbose=0
TraceOutputFileEnable=1
AS3Trace=0
TraceOutputBuffered=0
AS3StaticProfile=0
Then in Vizzy you have to set up the path to the log. On my windows 7 machine it is here:
C:\Users\MyUserName\AppData\Roaming\Macromedia\Flash Player\Logs\flashlog.txt
It may be different depending on your operating system.
Good luck, and report back if you Vizzy gives you any new information.