我试图通过创建一个包含每个声音的文件路径(或名称)的字符串数组来实例化一堆声音。
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);
}
然后这样调用:
//Stop a sound
channelByName["sound1.mp3"].stop();
//Play a sound
channelByName["sound2.mp3"] = soundByName["sound2.mp3"].play();
我当前的代码包含来自sound_completeHandler()函数的错误,指出未找到“name”属性。我无法弄清楚如何添加此名称属性,或者如何引用e.currentTarget。
答案 0 :(得分:2)
您的代码分为3部分:
soundByName是一个对象,您正在进行soundByName.soundName=new Sound()
=&gt;您正在soundByName中创建名为soundName的字段。
使用soundByName[soundName]=new Sound();
表示创建一个名称取自变量coundName的字段。
您正在使用channelByName使用channelByName[channelName]=value;
然后你想关联你名字中的soundChannel
,它无法正常工作Sound
对象没有这样的字段。使用字典将声音与名称相关联。
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]);
}