Search code examples
androidactionscript-3flashfilereference

as3 Air for Android downloading and saving remote files


The Code below downloads an mp3 to your phone from a server using as3 Air For Android. I want to use these files later in the app so I have the following question:

How can I make it so the files save to a particular folder in the android app rather than a box opening for the user to choose a location?

import flash.net.FileReference;

/// It can be an mp3,jpg, png, etc... just change the url
/// and the extension name. nice huh?
var yourFileLocation = "http://YourWeb.com/YourSong.mp3";
var yourFileName = "YourSong.mp3";

var daFile:FileReference = new FileReference();
daFile.download(new URLRequest(yourFileLocation), yourFileName);

Would also be sweet to monitor this progress, when it starts, stops and progress but I think an eventListener might work with that.


Solution

  • The Following Code downloads an mp3 from a remote url and makes a folder called .007(You can change the name or add many or no folders). Then it saves to that location.

    import flash.filesystem.*;
    /// Change the line below to point to your mp3 online
    var urlString:String = "http://YourWebsite.com/YourSound.mp3";
    var urlReq:URLRequest = new URLRequest(urlString);
    var urlStream:URLStream = new URLStream();
    var fileData:ByteArray = new ByteArray();
    urlStream.addEventListener(Event.COMPLETE, loaded);
    urlStream.load(urlReq);
    
    function loaded(event:Event):void
    {
        urlStream.readBytes(fileData, 0, urlStream.bytesAvailable);
        writeAirFile();
    }
    
    function writeAirFile():void
    { 
        // Change the folder path to whatever you want plus name your mp3
        // If the folder or folders does not exist it will create it.
        var file:File = File.userDirectory.resolvePath(".007/Yahoo.mp3");
        var fileStream:FileStream = new FileStream();
        fileStream.open(file, FileMode.WRITE);
        fileStream.writeBytes(fileData, 0, fileData.length);
        fileStream.close();
        trace("The file is written.");
    }
    

    P.S. REMEMBER TO GRANT THE CORRECT PERMISSIONS USING ANDROID IN THE APP