Thursday, October 27, 2011

Dynamically loading audio from different locations in ApplicationStorageDirectory

Similar to my last post about getting data from different locations, this time, instead of trying to load images, i'm trying to load audio clips.  It took a little bit of finagling, but I finally have it.  Just a quick bit of back story, I am downloading a zip file and unzipping contents into my app storage directory in folders.  If I reference the directory, I need to adjust the file.nativePath for that.  Enough talk, here's the code:

_file.nativePath     = _file.nativePath + _audio;
                req                 = new URLRequest(_file.url);
                s                     = new Sound(req,context);

over and over I tried to just make the URLRequest be the _file.nativePath + _audio and kept getting the most awful Error #2032 Stream Error (which explains nothing and is not helpful).  Finally I came across a forum post that explained that the URLRequest needs the _file.url, otherwise it appends this app:/ to my string, which bombs out.  So i can adjust the nativepath, and then use the url.  ta-da!!!

Loading images from applicationStorageDirectory in Flex Mobile

I have to say, without a doubt, this was one of the most confounding things I've worked on in a long, long, long time. In a project for my client, I have to be able to store zip files filled w/ media assets, then be able to load audio or pictures at runtime.

 Sounds easy, right? Wrong :(

 Loading a picture has never been this painful in my life. It turns out, I can add the image to the stage (which for some reason is not respecting my skin, contentgroup, or vertical layout settings). Regardless, I can finally load any stored image via this "not-so" simple routine.  One caveat I have is, I am downloading images in zip format, and using a utility to unpackage them into the storage directory in folders.  originally I though that would be a problem, but it turns out, because I can update the file.nativePath with the new folder, this works just fine.

var fl:File = File.applicationStorageDirectory;
fl.nativePath = fl.nativePath + _image;
var bytes:ByteArray = new ByteArray();
var filestream:FileStream = new FileStream();
try{, FileMode.READ);
filestream.readBytes(bytes, 0, filestream.bytesAvailable);
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, showPic);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
}catch (e){
trace("xml badly formed");

and in my showPic method:

loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, showPic);
var bitmapData:BitmapData = new BitmapData(loader.content.width,loader.content.height, true, 0x000000);
bitmapData.draw(loader.content, new Matrix(),null,null,null,true);
img.source = new Bitmap(bitmapData);

Honestly, painful, but it gets the job done.  Now to load audio dynamically from saved files is another story for another post:)