Actionscript Loading/Calling Sounds From String Array
i'm attempting to instantiate a bunch of sounds by creating a string array containing each sound's filepath (or name).
var soundByName:Object = {};
var channelByName:Object = {};
var soundName:String;
var channelName:String;
loadSounds();
function loadSounds():void
{
var files:Array = new Array("sound1.mp3", "sound2.mp3"); //etc.
for (var i:int = 0; i < files.length; 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(e:Event):void
{
channelName = e.currentTarget.name;
channelByName.channelName = new SoundChannel();
}
function sound_ioErrorHandler(e:IOErrorEvent):void
{
trace("Failed To Load Sound:" + e.currentTarget.name);
}
then called like this:
//Stop a sound
channelByName["sound1.mp3"].stop();
//Play a sound
channelByName["sound2.mp3"] = soundByName["sound2.mp3"].play();
my current code contains an error from the sound_completeHandler() function stating that the 'name' property wasn't found. i can't figure out how to add this name property, or how else to reference the e.currentTarget.
Your code is wrong in 3 parts:
soundByName is an Object and you are doing a
soundByName.soundName=new Sound()
=> you are creating a field named soundName within soundByName. UsesoundByName[soundName]=new Sound();
which mean create a field with the name taken from the variable coundName.You are doing the same with channelByName use
channelByName[channelName]=value;
Then you want to associate a
soundChannel
from your name, it can't workSound
object have no such field. Use a dictionary where you will associating the sound with the name.var nameBySound:Dictionary = new Dictionary(); var soundByName:Object = {}; var channelByName:Object = {}; loadSounds(); function loadSounds():void { var files:Array = ["sound1.mp3", "sound2.mp3"]; //etc. for (var i:int = 0; i < files.length; i++) { var soundName:String = files[i]; var sound:Sound=new Sound(); nameBySound[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=nameBySound[e.currentTarget]; channelByName[soundName] = new SoundChannel(); } function sound_ioErrorHandler(e:IOErrorEvent):void { trace("Failed To Load Sound:" + nameBySound[e.currentTarget]); }
精彩评论