The filename of a just loaded file via FileReference is not available - apache-flex

To load 3 files locally into the Flash Player, one might using something like this manage the sequence after the user has chosen the files...
private function uploadList(evt:Event):void{
var arr:Array = fileReferenceList.fileList;
for each(var item:FileReference in arr){
item.addEventListener(Event.COMPLETE, onFileLoadComplete);
item.load();
}
}
// Step 2 - go ahead and load the file and wait for step 3...this will be called three times in this use-case.
private function onFileLoadComplete(e:Event):void {
  var loader:Loader = new Loader();
  loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onDataLoadComplete);
  loader.loadBytes(FileReference(e.target).data);
}
// Step 3 - Flash Player has loaded the file and is ready for processing...
// this example is an image being stuffed into a BitmapData object...
private function onDataLoadComplete(e:Event):void {
var bitmapData:BitmapData = Bitmap(e.target.content).bitmapData;
var loader:Loader = Loader(e.target.loader);
...
}
// Step 4 - Where is the filename and file byte size located for each file passing through Step 3?
I've not been able to locate this data in existing objects.
My own resolution....
I stuff the info into a simple dictionary and retrieve it later.
Perhaps there are other solutions out there?
private function onFileLoadComplete(e:Event):void {
if(FileReference(e.target).data.length == 0){
return;
}
  var loader:Loader = new Loader();
filenameDict[loader] = String(FileReference(e.target).name);
  loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onDataLoadComplete);
  loader.loadBytes(FileReference(e.target).data);
}
private function onDataLoadComplete(e:Event):void {
var bitmapData:BitmapData = Bitmap(e.target.content).bitmapData;
var loader:Loader = Loader(e.target.loader);
var file:String = filenameDict[loader];
delete filenameDict[loader];

You can do it with arrays but as you can see from the code, Dictionary is the easier way.
var files:Array = [];
var loaders:Array = [];
private function onFileLoadComplete(e:Event):void
{
var loader:Loader = new Loader();
files.push(e.target);
loaders.push(loader);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onDataLoadComplete);
loader.loadBytes(FileReference(e.target).data);
}
private function onDataLoadComplete(e:Event):void
{
var bitmapData:BitmapData = Bitmap(e.target.content).bitmapData;
var loader:Loader = Loader(e.target.loader);
var index:Number = loaders.indexOf(loader);
var file:String = FileReference(files[index]).name;
/*
* Clear the arrays to get rid of unwanted references that might
* prevent them from being garbage collected.
* */
files.splice(index);
loaders.splice(index);
}
I was oblivious to FP10's FileReference when I made the first version of this post.

Related

Pulling Docs List from Collection

I there a way to display specific collection files and URL in a spreadsheet?
I have already tried running a basic DocList Search script but I need something to be more direct. I would need the script to display File Name, Collections It belongs to, and URL.
The end goal of this project is to create a Google site that allows users to click a Image link launching a simple "Copy Function" this copy function will create a copy of that document for the user in there individual drive. However we will be doing this on a mass scale of over 1,000 documents. So pulling the information and having it more organized would be alot easier then copying the URL section out of each document and then pasting it into the scripts functions.
here is a script I wrote quite a while ago that does (a bit more than ) what you want... it shows the IDs but you can easily change it to show the urls instead.
// G. Variables
var sh = SpreadsheetApp.getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lastrow = ss.getLastRow();
//
//
//
function onOpen() {
var menuEntries = [ {name: "generic doclist", functionName: "gendoclisttest"},
{name: "categorized list(spreadsheet/docs)", functionName: "doclistcat"},
{name: "Search DocList", functionName: "searchUI"},
];
ss.addMenu("Utilities", menuEntries);//
}
//
// Build a simple UI to enter search item and show results + activate result's row
function searchUI() {
var app = UiApp.createApplication().setHeight(130).setWidth(400);
app.setTitle("Search by name or folder name");
var panel = app.createVerticalPanel();
var txtBox = app.createTextBox().setFocus(true).setWidth("180");
var label=app.createLabel(" Eléments à rechercher :")
var label=app.createLabel(" Item to search for :")
panel.add(label);
txtBox.setId("item").setName("item");
var label0=app.createLabel("Row").setWidth("40");
var label1=app.createLabel("Doc Name").setWidth("180");
var label2=app.createLabel("Doc ID").setWidth("180");
var hpanel = app.createHorizontalPanel();
hpanel.add(label0).add(label1).add(label2);
//
var txt0=app.createTextBox().setId("lab0").setName("0").setWidth("40");
var txt1=app.createTextBox().setId("lab1").setName("txt1").setWidth("180");
var txt2=app.createTextBox().setId("lab2").setName("txt2").setWidth("180");
var hpanel2 = app.createHorizontalPanel();
hpanel2.add(txt0).add(txt1).add(txt2);
var hidden = app.createHidden().setName("hidden").setId("hidden");
var subbtn = app.createButton("next ?").setId("next").setWidth("250");
panel.add(txtBox);
panel.add(subbtn);
panel.add(hidden);
panel.add(hpanel);
panel.add(hpanel2);
var keyHandler = app.createServerHandler("click");
txtBox.addKeyUpHandler(keyHandler)
keyHandler.addCallbackElement(panel);
//
var submitHandler = app.createServerHandler("next");
subbtn.addClickHandler(submitHandler);
submitHandler.addCallbackElement(panel);
//
app.add(panel);
ss.show(app);
}
//
function click(e){
var row=ss.getActiveRange().getRowIndex();
var app = UiApp.getActiveApplication();
var txtBox = app.getElementById("item");
var subbtn = app.getElementById("next").setText("next ?")
var txt0=app.getElementById("lab0").setText('--');
var txt1=app.getElementById("lab1").setText('no match').setStyleAttribute("background", "white");// default value to start with
var txt2=app.getElementById("lab2").setText('');
var item=e.parameter.item.toLowerCase(); // item to search for
var hidden=app.getElementById("hidden")
var data = sh.getRange(2,1,lastrow,8).getValues();// get the 8 columns of data
for(nn=0;nn<data.length;++nn){ ;// iterate trough
if(data[nn].toString().toLowerCase().match(item.toString())==item.toString()&&item!=''){;// if a match is found in one of the 3 fields, break the loop and show results
var datarow=data[nn]
for(cc=0;cc<datarow.length;++cc){
if(datarow[cc].toString().toLowerCase().match(item.toString())==item.toString()&&item!=''){break}
}
var idx=cc
txt0.setText(nn+2);
txt1.setText(data[nn][idx]).setStyleAttribute("background", "cyan");
txt2.setText(data[nn][idx+1]);
sh.getRange(nn+2,idx+1).activate();
subbtn.setText("found '"+item+"' in row "+Number(nn+2)+", next ?");
hidden.setValue(nn.toString())
break
}
}
return app ;// update UI
}
function next(e){
var row=ss.getActiveRange().getRowIndex();
var app = UiApp.getActiveApplication();
var txtBox = app.getElementById("item");
var subbtn = app.getElementById("next").setText("no other match")
var hidden=app.getElementById("hidden");
var start=Number(e.parameter.hidden)+1;//returns the last search index stored in the UI
var item=e.parameter.item.toLowerCase(); // item to search for
var txt0=app.getElementById("lab0");
var txt1=app.getElementById("lab1").setStyleAttribute("background", "yellow");
var txt2=app.getElementById("lab2");
var data = sh.getRange(2,1,lastrow,8).getValues();// get the 3 columns of data
for(nn=start;nn<data.length;++nn){ ;// iterate trough
if(data[nn].toString().toLowerCase().match(item.toString())==item.toString()&&item!=''){;// if a match is found in one of the 3 fields, break the loop and show results
var datarow=data[nn]
for(cc=0;cc<datarow.length;++cc){
if(datarow[cc].toString().toLowerCase().match(item.toString())==item.toString()&&item!=''){break}
}
var idx=cc
txt0.setText(nn+2);
txt1.setText(data[nn][idx]).setStyleAttribute("background", "cyan");
txt2.setText(data[nn][idx+1]);
sh.getRange(nn+2,idx+1).activate();
subbtn.setText("found '"+item+"' in row "+Number(nn+2)+", next ?");
hidden.setValue(nn.toString())
break
}
}
return app ;// update UI
}
//
function gendoclisttest(){
sh.getRange(1,1).setValue('.');// usefull to allow for 'clear' if page is empty
sh.getRange(1,1,ss.getLastRow(),ss.getLastColumn()).clear().setWrap(false).setBorder(false,false,false,false,false,false);// clears whole sheet
var doclist=new Array();
var folders=DocsList.getFolders()
for(ff=0;ff<folders.length;++ff){
doclist=folders[ff].getFiles(0,2000)
var names = new Array();
for (nn=0;nn<doclist.length;++nn){
names.push([doclist[nn].getName(),doclist[nn].getId()]);
}
if (names.length>0){
names.sort();
var row=ss.getLastRow()+1;
sh.getRange(row,1,1,3).setValues([["Folders","Generic Doc Names","ID"]]).setBorder(false,true,true,true,true,true).setBackgroundColor("#dddddd");
sh.getRange(row+1,1).setValue(folders[ff].getName())
sh.getRange(row+1,2,names.length,2).setValues(names);
}
}
doclist=DocsList.getRootFolder().getFiles(0,2000)
var names = new Array();
for (nn=0;nn<doclist.length;++nn){
names.push([doclist[nn].getName(),doclist[nn].getId()]);
}
if (names.length>0){
names.sort();
var row=ss.getLastRow()+1;
sh.getRange(row,1,1,3).setValues([["Root","Generic Doc Names","ID"]]).setBorder(false,true,true,true,true,true).setBackgroundColor("#dddddd");
sh.getRange(row+1,2,names.length,2).setValues(names);
}
}
//
function doclistcat(){
var doclist=new Array();
var folders=DocsList.getFolders()
var zz=0;var nn=0
for(ff=0;ff<folders.length;++ff){
doclist=folders[ff].getFilesByType("spreadsheet",0,2000);
var names = new Array();
for (nn=0;nn<doclist.length;++nn){
names.push([doclist[nn].getName(),doclist[nn].getId()]);
}
if(names.length>0){
names.sort();
zz=zz+nn
var row=zz-nn+1
sh.getRange(row,4,1,3).setValues([["Folders","Spreadsheet Names","ID"]]).setBorder(true,true,true,true,true,true).setBackgroundColor("#dddddd");
sh.getRange(row+1,4).setValue(folders[ff].getName()).setB
sh.getRange(row+1,5,names.length,2).setValues(names);
}
}
doclist=DocsList.getRootFolder().getFilesByType("spreadsheet",0,2000);
var names = new Array();
for (nn=0;nn<doclist.length;++nn){
names.push([doclist[nn].getName(),doclist[nn].getId()]);
}
if(names.length>0){
names.sort();
zz=zz+nn
var row=zz-nn+1
sh.getRange(row,4,1,3).setValues([["Root","Spreadsheet Names","ID"]]).setBorder(true,true,true,true,true,true).setBackgroundColor("#dddddd");
sh.getRange(row+1,5,names.length,2).setValues(names);
}
//
var zz=0;var nn=0
for(ff=0;ff<folders.length;++ff){
doclist=folders[ff].getFilesByType("document",0,2000);
var names = new Array();
for (nn=0;nn<doclist.length;++nn){
names.push([doclist[nn].getName(),doclist[nn].getId()]);
}
if(names.length>0){
names.sort();
zz=zz+nn
var row=zz-nn+1
sh.getRange(row,7,1,3).setValues([["Folders","Text Document Names","ID"]]).setBorder(true,true,true,true,true,true).setBackgroundColor("#dddddd");
sh.getRange(row+1,7).setValue(folders[ff].getName()).setB
sh.getRange(row+1,8,names.length,2).setValues(names);
}
}
doclist=DocsList.getRootFolder().getFilesByType("document",0,2000);
var names = new Array();
for (nn=0;nn<doclist.length;++nn){
names.push([doclist[nn].getName(),doclist[nn].getId()]);
}
if(names.length>0){
names.sort();
zz=zz+nn
var row=zz-nn+1
sh.getRange(row,7,1,3).setValues([["Root","document Names","ID"]]).setBorder(true,true,true,true,true,true).setBackgroundColor("#dddddd");
sh.getRange(row+1,8,names.length,2).setValues(names);
}
}
//
//eof

Looping through an arraylist sourced from an XML file

I am reading in an XML file that is shown in the attached image. I'm reading it in using URLRequest, which works properly. The next thing I'd like to do is to populate an arraylist with all of the "project" nodes. I'm converting the XML to an array, but the source is showing the project as being in the [0] node and the arraylist's length is 1.
What's the proper way to do this so I can loop through all the projects in the arraylist?
private var xmlParameters:XML
private var xmlStoryMap:XMLList;
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
var params:Object;
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, xmlloader_onComplete_Handler);
xmlLoader.addEventListener(IOErrorEvent.IO_ERROR,IOError_handler);
xmlLoader.load(new URLRequest("myXML.xml"));
}
protected function xmlloader_onComplete_Handler(event:Event):void
{
var loader:URLLoader = URLLoader(event.target)
xmlParameters = new XML(loader.data);
xmlStoryMap = xmlParameters.projects;
initializeMap();
}
protected function initializeMap():void
{
var testlist:ArrayList = new ArrayList();
testlist.source = convertXMLtoArray(xmlStoryMap.project);
}
private function convertXMLtoArray(file:String):Array
{
var xml:XMLDocument = new XMLDocument(file);
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder;
var data:Object = decoder.decodeXML(xml);
var array:Array = ArrayUtil.toArray(data);
return array;
}
If you don't want to have a loop issue, use this instead
protected function xmlloader_onComplete_Handler(event:Event):void
{
var loader:URLLoader = URLLoader(event.target)
var xmlString:String = loader.data;
initializeMap(xmlString);
}
protected function initializeMap(xmlString:String):void
{
var testlist:ArrayList = new ArrayList();
testlist.source = convertXMLtoArray(xmlString);
}
private function convertXMLtoArray(xmlString:String):Array
{
var xmlDoc:XMLDocument = new XMLDocument(xmlString);
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder();
var data:Object = decoder.decodeXML(xmlDoc);
return ArrayUtil.toArray(data.storymap.projects.project);
}
For looping through the projects,
for each(var projectXML:XML in xmlParameters.projects.project)
{
// Do operation
}

Flex 3: Setting one arrayCollection to another is stalling the application

I'll just go ahead and C/P the entire function to ensure you guys see everything going on:
public function directorsPrepsToShow():void
{
var tempDPrepsAC:ArrayCollection = new ArrayCollection;
var dprepSD:Date = new Date;
var dprepED:Date = new Date;
var viewSD:Date = rightDate(startViewDate.getMonth(), startViewDate.getDate(), startViewDate.getFullYear());
var viewED:Date = rightDate(viewSD.getMonth(), viewSD.getDate() + 14, viewSD.getFullYear());
var newACIDs:String = new String;
var useACIDs:String = new String;
for each (var item:Object in dPrepAC)
{
dprepSD = textToDate(item[2]);
dprepED = rightDate(dprepSD.getMonth(), Number(dprepSD.getDate() + (item[3] - 1)), dprepSD.getFullYear());
if (dateCollider(dprepSD, dprepED, viewSD, viewED))
tempDPrepsAC.addItem(item as Array);
}
if (tempDPrepsAC.length != usePrepAC.length)
{
usePrepAC = new ArrayCollection();
usePrepAC = tempDPrepsAC;
Alert.show("HI");
}
}
This function is in a separate file, that's called from the main mxml via the following:
<mx:Script source="functions/dprep.as" />
The line that's causing the app to stall is "usePrepAC = tempDPrepAC;". usePrepAC is declared in the main mxml like this:
[Bindable] public var usePrepAC:ArrayCollection = new ArrayCollection;
Dose anybody see why this one line would cause the application to stall? If I comment out that line, the application loads fine (loads everything except for the information that this AC should contain). I've been looking at this now for about an hour, trying different ways to get the contents of tempDPrepsAC into usePrepAC - but nothing is working. I tried googling it, but found nothing :(
Thanks,
Brds
EDIT
dprep AC is declared in the main mxml like this:
[Bindable] public var dPrepAC:ArrayCollection = new ArrayCollection;
And the function that populates it is as follows:
public function createDirectorsPrepCollection(e:ResultEvent):void
{
var xmlList:XMLList = XML(e.result).directorsprep;
var dupString:String = "|";
var tempArray:Array = new Array;
for (var i:int = 0; i < xmlList.length(); i++)
{
if (dupString.indexOf(String("|" + xmlList[i].name.#id) + "|") == -1)
{
tempArray = new Array;
tempArray[0] = xmlList[i].prepDBID;
tempArray[1] = xmlList[i].projectDBID;
tempArray[2] = xmlList[i].startdate;
tempArray[3] = xmlList[i].numdays;
tempArray[4] = xmlList[i].positions;
dPrepAC.addItem(tempArray);
dupString += "|" + xmlList[i].prepDBID + "|";
}
}
directorsPrepsToShow();
}
This function is called by this:
<mx:HTTPService id="dprepHttp" url="{dprepXML}" resultFormat="e4x" makeObjectsBindable="true" result="createDirectorsPrepCollection(event)" />
dPrepAC is populating fine btw... I check it in a for each loop.
Try using following code:
usePrepAC.source = tempDPrepsAC.source;

load symbol of flash in flex at runtime

Hey people, I've this huge problem loading a symbol from a swf file in the application at runtime. I want to load it and pass it as a argument to another class where it could be used further. The symbol name is passed on from the array collection from the "o" object. Can anybody please tell me what's the right way to go about it.. Thanks in advance..!!
Following is the code for reference..
public override function Show(o:ObjectProxy):void
{
var _this:Weather;
var _super:ContentItem;
var item:WeatherItem;
var items:ArrayCollection;
var widgetCount:Number;
var headlineFontSize:int;
var conditionsIconThemeLoader:Loader;
this.m_weatherWidgetContainer = new HBox();
super.Show(o);
_this = this;
_super = super;
(undefined == o["HeadlineFontSize"]) ? headlineFontSize = 20 : headlineFontSize = o["HeadlineFontSize"];
if (undefined != o["direction"])
this.m_textDirection = o["direction"];
if (o.LargeUrl.Forecast is ArrayCollection)
items = ArrayCollection(o.LargeUrl.Forecast);
else
items = new ArrayCollection([o.LargeUrl.Forecast]);
widgetCount = this.m_computeWidgetSpace(items.length);
conditionsIconThemeLoader = new Loader();
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event):void
{
for(var i:uint = 0; i < widgetCount; i++)
{
var symbolClass:Class = e.currentTarget.loader.contentLoaderInfo.applicationDomain.currentDomain.getDefinition(int(items[i].condition)) as Class;
var symbolInstance:Sprite = new symbolClass();
item = new WeatherItem();
item.Show(items[i], headlineFontSize, symbolInstance, widgetCount);
_this.m_weatherWidgetContainer.addChild(item);
}
});
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void
{
Alert.show("Failure loading " + WidgetStylesheet.instance.Weather_Widget_Theme + ".swf");
});
// Attempt to load theme weather icon file
conditionsIconThemeLoader.load(new URLRequest("assets/animation/" + WidgetStylesheet.instance.Weather_Widget_Theme + ".swf"));
super.media.addChild(this.m_weatherWidgetContainer);
}
Heres the answer
public override function Show(o:ObjectProxy):void
{
var _this:Weather;
var _super:ContentItem;
var conditionsIconThemeLoader:Loader;
var loaderContext:LoaderContext;
this.m_weatherWidgetContainer = new HBox();
this.m_weatherWidgetContainer.percentHeight = 100;
this.m_weatherWidgetContainer.percentWidth = 100;
super.Show(o);
_this = this;
(undefined == o["HeadlineFontSize"]) ? this.m_headlineFontSize = 20 : this.m_headlineFontSize = o["HeadlineFontSize"];
if (undefined != o["direction"])
this.m_textDirection = o["direction"];
if (o.LargeUrl.Forecast is ArrayCollection)
this.m_items = o.LargeUrl.Forecast;
else
this.m_items = new ArrayCollection([o.LargeUrl.Forecast]);
conditionsIconThemeLoader = new Loader();
loaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.m_loaderSuccess);
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.m_loaderFail);
// Attempt to load theme weather icon file
conditionsIconThemeLoader.load(new URLRequest("assets/animation/" + WidgetStylesheet.instance.Weather_Widget_Theme + ".swf"), loaderContext);
this.m_weatherWidgetContainer.addEventListener(FlexEvent.CREATION_COMPLETE, this.m_drawHorizontalLine);
super.media.addChild(this.m_weatherWidgetContainer);
}

Dynamically Creating Variables In Actionscript 3.0?

i'm loading several sound files, and want to error check each load. however, instead programming each one with their own complete/error functions, i would like them to all use the same complete/error handler functions.
a successfully loaded sound should create a new sound channel variable, while an unsuccessfully loaded sound will produce a simple trace with the name of the sound that failed to load. however, in order to do this, i need to dynamically create variables, which i haven't yet figured out how to do.
here's my code for my complete and error functions:
function soundLoadedOK(e:Event):void
{
//EX: Sound named "explosion" will create Sound Channel named "explosionChannel"
var String(e.currentTarget.name + "Channel"):SoundChannel = new SoundChannel();
}
function soundLoadFailed(e:IOErrorEvent):void
{
trace("Failed To Load Sound:" + e.currentTarget.name);
}
-=-=-=-=-=-=-=-=-
UPDATED (RE: viatropos)
-=-=-=-=-=-=-=-=-
can not find the error.
TypeError: Error #1009: Cannot access a property or method of a null object reference. at lesson12_start_fla::MainTimeline/loadSounds() at lesson12_start_fla::MainTimeline/frame1():
//Sounds
var soundByName:Object = {};
var channelByName:Object = {};
var soundName:String;
var channelName:String;
loadSounds();
function loadSounds():void
{
var files:Array = ["robotArm.mp3", "click.mp3"];
var i:int = 0;
var n:int = files.length;
for (i; i < n; i++)
{
soundName = files[i];
soundByName[soundName] = new Sound();
soundByName[soundName].addEventListener(Event.COMPLETE, sound_completeHandler);
soundByName[soundName].addEventListener(IOErrorEvent.IO_ERROR, sound_ioErrorHandler);
soundByName[soundName].load(new URLRequest(soundName));
}
}
function sound_completeHandler(event:Event):void
{
channelName = event.currentTarget.id3.songName;
channelByName[channelName] = new SoundChannel();
}
function sound_ioErrorHandler(event:IOErrorEvent):void
{
trace("Failed To Load Sound:" + event.currentTarget.name);
}
You can do this a few ways:
Storing your SoundChannels in an Array. Good if you care about order or you don't care about getting them by name.
Storing SoundChannels by any name in an Object. Good if you want to easily be able to get the by name. Note, the Object class can only store keys ({key:value} or object[key] = value) that are Strings. If you need Objects as keys, use flash.utils.Dictionary, it's a glorified hash.
Here's an example demonstrating using an Array vs. an Object.
var channels:Array = [];
// instead of creating a ton of properties like
// propA propB propC
// just create one property and have it keep those values
var channelsByName:Object = {};
function loadSounds():void
{
var files:Array = ["soundA.mp3", "soundB.mp3", "soundC.mp3"];
var sound:Sound;
var soundChannel:SoundChannel;
var i:int = 0;
var n:int = files.length;
for (i; i < n; i++)
{
sound = new Sound();
sound.addEventListener(Event.COMPLETE, sound_completeHandler);
sound.addEventListener(IOErrorEvent.IO_ERROR, sound_ioErrorHandler);
sound.load(files[i]);
}
}
function sound_completeHandler(event:Event):void
{
// option A
var channelName:String = event.currentTarget.id3.songName;
// if you want to be able to get them by name
channelsByName[channelName] = new SoundChannel();
// optionB
// if you just need to keep track of all of them,
// and don't care about the name specifically
channels.push(new SoundChannel())
}
function sound_ioErrorHandler(event:IOErrorEvent):void
{
trace("Failed To Load Sound:" + event.currentTarget.name);
}
Let me know if that works out.
//Load Sounds
var soundDictionary:Dictionary = new Dictionary();
var soundByName:Object = new Object();
var channelByName:Object = new Object();
loadSounds();
function loadSounds():void
{
var files:Array = ["robotArm.mp3", "click.mp3"]; //etc.
for (var i:int = 0; i < files.length; i++)
{
var soundName:String = files[i];
var sound:Sound=new Sound();
soundDictionary[sound] = soundName;
soundByName[soundName] = sound;
sound.addEventListener(Event.COMPLETE, sound_completeHandler);
sound.addEventListener(IOErrorEvent.IO_ERROR, sound_ioErrorHandler);
sound.load(new URLRequest(soundName));
}
}
function sound_completeHandler(e:Event):void
{
var soundName:String=soundDictionary[e.currentTarget];
channelByName[soundName] = new SoundChannel();
}
function sound_ioErrorHandler(e:IOErrorEvent):void
{
trace("Failed To Load Sound:" + soundDictionary[e.currentTarget]);
}
//Play Sound
channelByName["robotArm.mp3"] = soundByName["robotArm.mp3"].play();
//Stop Sound
channelByName["robotArm.mp3"].stop();

Resources