AS3 SWFs Loading External Files; Change default location - actionscript-3

If I have a SWF and an XML file sitting in the same folder, is there a way to get the loader to use the location of the SWF as its starting point for loading the external file (as opposed to the HTML file upon which the SWF plays)? We are copying a group of web sites and some of the paths have unique page codes, but if the SWFs would just look in their own folder they would run fine. :)
Thank you!
Chris

Could try this.
var base:String = unescape( LoaderInfo( this.root.loaderInfo ).url ); // url of SWF
// now we need to remove the SWF name from the url
var lastSlash:uint = Math.max( this.base.lastIndexOf( "\\" ), this.base.lastIndexOf( "/" ) );
return( base.substr( 0, lastSlash + 1 ) );
That will take the url of the SWF, loop through it and find the last "\" or "/" to determine where the swf file name starts, and set the base equal to the path of the SWF.
And then change all relative URLRequests from
var url:URLRequest = new URLRequest( "assets/blah/blah/img.png" );
to
var url:URLRequest = new URLRequest( base + "assets/blah/blah/img.png" );
This would be something I would add as a static property of your application class so that you are only accessing a string and not doing any casting or unicode escaping or anything repeatedly. Just run it once at start up and throw it as a static var because it will never change.
(I did test this and it works, at least locally. I see no reason why it would behave any differently with a URL from the web, however)

Related

AS3 SharedObject read/write file location change

I’m using the following AS3 code to write and read data in two arrays to a local file, using Animate CC 2019 on Windows 10 and AIR 30.0 for Desktop/Flash (.swf) publishing settings. I use two input text boxes, input1 & input2, to add new data to the arrays.
When I test the FLA, the data file created has a .sol extension and is placed in a folder path:
C:\Users\username\AppData\Roaming\FLA filename\Local Store#SharedObjects\FLA filename.swf\
If I publish and install the program using an .air installer package, the exact same file, in the same folder path, is also accessed by the installed version of the program. Same location is used if I install on another computer running Windows 7, so the file location seems pretty consistent.
Question:
How can I force the code to save to a different location on the local hard drive on Windows? For example, in the documents folder or to create a new folder on the system drive and save the file there? Or, even better, prompt the user to choose the folder and file himself?
Please consider I’m looking for an answer using SharedObject, if possible, and not alternative methods like URLLoader, File, FileStream, FileMode. The reason is this way I can store multiple array contents in a file, without having to deal with the in-file data arrangement. So, I can read back the data for each array easily as shown below.
Thanks in advance
This is the code I use to access the local file:
var datavariable:SharedObject = SharedObject.getLocal("filiename");
var data1:Array = new Array ();
var data2:Array = new Array ();
btn_read.addEventListener(MouseEvent.CLICK, readfromfile);
btn_write.addEventListener(MouseEvent.CLICK, writetofile);
btn_new.addEventListener(MouseEvent.CLICK, newentry);
//To add new data from input text boxes to the arrays:
function newentry(e:Event):void
{
data1.push(input1.text);
data2.push(input2.text);
}
//To write to the local file:
function readfromfile(e:Event):void
{
data1 = datavariable.data.d1
data2 = datavariable.data.d2
}
//To read from the local file:
function writetofile(e:Event):void
{
datavariable.data.d1 = data1
datavariable.data.d2 = data2
datavariable.flush();
}
I don't know of a way of changing the shared object storage location. That mechanism is designed to be abstracted out from the developer.
Since you are using AIR, you can actually forget shared objects, and just write your own files anywhere your app has permission to do so. You can do this using the same format as shared object and don't have to worry about in file data arrangement (you save an object, you read back an object - just like Shared Object does), the only difference is you load/save the file where you choose.
Here is an example:
function writetofile(e:Event):void
{
//create an object that holds your data, this will act the same as the 'data' value of a shared object
var saveObject = {
d1: data1,
d2: data2
}
//using the File and FileStream classes to read/save files
var file:File = File.applicationStorageDirectory.resolvePath("saveData.data"); //or where and whatever you want to store and call the save file
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
fileStream.writeObject(saveObject); //write the object to this file
fileStream.close(); //close the File Stream
}
function readfromfile(e:Event):void
{
var file:File = File.applicationStorageDirectory.resolvePath("saveData.data");
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var savedObject = fileStream.readObject();
fileStream.close();
data1 = savedObject.d1;
data2 = savedObject.d2;
}
If you want to save complex objects (objects that aren't primitives), you need to register the class first. This goes for shared objects as well. See this answer for example of that.

Error #2035 URL not found - file path configuration

I try to open a swf from another swf. They are on the same folder. Here is the code block I am trying to get the file.
var newRequest:URLRequest;
var path:String = "mahmut"+".swf";
newRequest = new URLRequest(path);
newLoader = new Loader;
newLoader.load(newRequest);
newLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeFn);
newLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, camaluriFn);
function camaluriFn(e:IOErrorEvent)
{
trace("Error: " + String(e));
}
and trace throws Error #2035: URL Not Found. URL: app:/mahmut.swf
So how can I give right path and it can open display successfully?
Doesn't matter where those files are, what matters is from where they are loaded. In your case all local paths are from the app root no matter what. If you swf are in folder "myswfs" then the right path is not just "mahmut"+".swf" but "myswf/smahmut.swf".

playing a single audio file on windows phone

I use this code for playing single mp3 audio file and i used MediaElement:
Uri Path = new Uri("AudioFiles/music.mp3", UriKind.Relative);
SoundPlayer.Source = Path;
SoundPlayer.Play();
but i got this error :
An exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll but was not handled in user code
Additional information: The given System.Uri cannot be converted into a Windows.Foundation.Uri.
what is wrong with that ?
Thanks
Depending on the location of your file, you may need a different Uri scheme. Try:
SoundPlayer.Source = new Uri(#"ms-appdata:///local/AudioFiles/music.mp3"); // if your file is in IsolatedStorage
SoundPlayer.Source = new Uri(#"ms-appx:///AudioFiles/music.mp3"); // if your file is a Build-in content
Note also that you don't need SoundPlayer.Play() if SoundPlayer.Autoplay is set to true (default setting). In case it's false - you will have to start to play manually in MediaOpened event not just after setting the Source.
Uri Path = new Uri("/AudioFiles/music.mp3", UriKind.Relative);
You are forgetting a "/" before AudioFiles.

as3 selecting a file dynamically

i need to select a video file and convert it to a byte array. the file i am trying to select has been recorded by the cameraUi interface. i can get the path to the file using
fileName = media.file.url;
readFileIntoByteArray(filePath, inBytes);
when i am passing it into the byte array i need to select directory first and then pass in the the rest of the path.
private function readFileIntoByteArray(fileName:String, data:ByteArray):void
{
var inFile:File = File.userDirectory;
inFile = inFile.resolvePath(fileName);
trace (inFile.url);
inStream.open(inFile , FileMode.READ);
inStream.readBytes(data);
}
this leads to duplication of the first part of the path.
i want to keep this dynamic as it will be run on different devices. i hard coded the file into the the variables section of flash debugger and it worked also i get an error if i leave out file.userDirectory
thanks in advance any help would be appreciated
You should always use File.applicationStorageDirectory instead of File.userDirectory. Due to security risk will vary to vary different device. File.applicationStorageDirectory will work any device.
Robust way of working with filepath
var firstPartPath:String = File.applicationStorageDirectory.nativePath;
var fullPath:String = File.applicationStorageDirectory.resolvePath("fileName.jpg").nativePath;
var expectedPath:String = fullPath.replace(firstPartPath,""); // "/fileName.jpg"
Here expectedPath value you should pass around your project instead of hard code value like c:\users\XXXX\ and save into database also use expectedPath value.
For latter access file just pass only expectedPath.
var inFile:File = File.applicationStorageDirectory.resolvePath(expectedPath);
Needn't worry about forward and backword slashes. File resolvePath() take care for you.
private function readFileIntoByteArray(fileName:String, data:ByteArray):void
{
var inFile:File = File.applicationStorageDirectory.resolvePath(fileName);
trace (inFile.url);
trace (inFile.nativePath);
trace (inFile.exists); //if file present true else false.
inStream.open(inFile , FileMode.READ);
inStream.readBytes(data);
}

Flash Builder will not read local JSON file . .

So I've tried to build a small utility to view the contents of a JSON file in an easy-to-understand manner (for non-tech people).
I have Googled far and wide, high and low, but every example that shows how to consume a JSON file in Flash Builder uses the HTTP service, pointing to a file on the web.
Here I am, sitting in front of my MacBook, wondering why I can't make this work. In the documentation I've found (sort of relating to this issue), they always show Windows examples, and they seem to work fine:
C://me/projects/json/my_json.json
Perhaps I'm completely missing the obvious, but is this possible on a Mac as well?
I've tried
file:///Users/me/projects/json/my_json.json
That doesn't work. I've tried some "resolve to path" syntax, but the HTTP service does not seem to allow for anything but file paths in quotes.
Would anyone be able to pint me in the right direction?
Use the File API. It's really easy, here's a quick code sample:
// Get a File reference, starting on the desktop.
// If you have a specific file you want to open you could do this:
// var file:File = File.desktopDirectory.resolvePath("myfile.json")
// Then skip directly to readFile()
var file:File = File.desktopDirectory;
// Add a listener for when the user selects a file
file.addEventListener(Event.SELECT, onSelect);
// Add a listener for when the user cancels selecting a file
file.addEventListener(Event.CANCEL, onCancel);
// This will restrict the file open dialog such that you
// can only open .json files
var filter:FileFilter = new FileFilter("JSON Files", "*.json");
// Open the file browse dialog
file.browseForOpen("Open a file", [filter]);
// Select event handler
private function onSelect(e:Event):void
{
// Remove listeners on e.currentTarget
// ...
// Cast to File
var selectedFile:File = e.currentTarget as File;
readFile(selectedFile);
}
private function onCancel(e:Event):void
{
// Remove listeners on e.currentTarget
// ...
}
private function readFile(file:File):void
{
// Read file
var fs:FileStream = new FileStream();
fs.open(selectedFile, FileMode.READ);
var contents:String = fs.readUTFBytes(selectedFile.size);
fs.close()
// Parse your JSON for display or whatever you need it for
parseJSON(contents);
}
You hinted at this in your post about examples being for Windows and you being on a Mac but I'll state it explicitly here: you should always use the File API because it is cross platform. This code will work equally well on Windows and Mac.