我试图通过创建包含每个声音的文件路径(或名称)的字符串数组来实例化一堆声音。
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。
最佳答案
您的代码有3个部分是错误的:
soundByName.soundName=new Sound()
=>,您将在soundByName中创建一个名为soundName的字段。使用
soundByName[soundName]=new Sound();
意味着创建一个字段,该字段的名称取自变量coundName。 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]);
}
关于actionscript-3 - Actionscript从字符串数组加载/调用声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2395226/