Search code examples
actionscript-3airdirectory

as3 air check if file is loaded


How can I run code then the array is ready?

When I run the following code I get an error saying: TypeError: Error #1010: A term is undefined and has no properties.

import flash.filesystem.File;

var desktop:File = File.applicationDirectory.resolvePath("sounds/drums");

var sounds:Array = desktop.getDirectoryListing();

for (var i:uint = 0; i < sounds.length; i++)
   {
    trace(sounds[i].nativePath); // gets the path of the files
    trace(sounds[i].name);// gets the name
   }


var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
mySound.load(new URLRequest("sounds/drums/"+sounds[i].name+""));
myChannel = mySound.play();

Solution

  • I usually use something like the below, each time a sound is loaded it is stored and a counter is incremented, once all sounds are loaded you can dispatch an event or start playing any of the sounds stored in loadedSounds.

    var sounds:Array = desktop.getDirectoryListing();
    
    var loadedSounds:Object = {};
    var soundsLoaded:int = 0;
    
    for (var i:uint = 0; i < sounds.length; i++)
    {
        var mySound:Sound = new Sound();
        mySound.addEventListener(Event.COMPLETE, onSoundLoaded);
        mySound.load(new URLRequest("sounds/drums/"+sounds[i].name));
    }
    
    private function onSoundLoaded(e:Event):void
    {
        var loadedSound = e.target as Sound;
        // just get the file name without path and use it as key
        var lastIndex:int = loadedSound.url.lastIndexOf("/");
        var key:String = loadedSound.url.substr(lastIndex+1);
    
        // store sounds for later reference
        loadedSounds[key] = loadedSound ;
    
        soundsLoaded++;
        if (soundsLoaded == sounds.length)
        {
            //all sounds loaded, can start playing
        }
    }