基于AS3的Android AIR数学APP:简化多帧题目音效播放方法问询
高效实现题目音效序列播放的方案
既然你要处理300多帧的重复音效逻辑,每帧写SOUND_COMPLETE事件确实太折腾人了——咱们可以把音效播放的核心逻辑封装成通用工具,让每帧只需要一行代码就能搞定。下面是具体的实现步骤:
1. 先把已加载的音效映射成可快速查找的集合
首先,把你已经加载好的数字、运算符音效放进一个字典里,这样后续可以直接通过题目里的字符(比如"4"、"+")快速拿到对应的Sound对象:
// 在全局位置(比如主时间轴第一帧)定义这个字典 var soundLookup:Dictionary = new Dictionary(); // 映射数字音效 soundLookup["0"] = DigitSound0; soundLookup["1"] = DigitSound1; soundLookup["2"] = DigitSound2; soundLookup["3"] = DigitSound3; soundLookup["4"] = DigitSound4; soundLookup["5"] = DigitSound5; soundLookup["6"] = DigitSound6; soundLookup["7"] = DigitSound7; soundLookup["8"] = DigitSound8; soundLookup["9"] = DigitSound9; // 映射运算符音效 soundLookup["+"] = DigitSoundplus; soundLookup["-"] = DigitSoundminus;
2. 封装两个核心函数
接下来写两个通用函数:一个负责把题目文本拆成音效队列,另一个负责按顺序播放队列里的音效。
解析题目文本为音效队列
这个函数会遍历题目字符串的每个字符,把对应的音效对象收集到数组里:
function getSoundQueueFromQuestion(questionText:String):Array { var soundQueue:Array = []; for (var i:int = 0; i < questionText.length; i++) { var currentChar:String = questionText.charAt(i); // 如果当前字符有对应的音效,就加入队列 if (soundLookup[currentChar]) { soundQueue.push(soundLookup[currentChar]); } } return soundQueue; }
按顺序播放音效队列
用递归的方式处理SOUND_COMPLETE事件,自动播放下一个音效,直到队列清空:
function playSoundSequence(soundQueue:Array):void { // 队列空了就停止 if (soundQueue.length === 0) return; // 取出队列第一个音效播放 var currentSound:Sound = soundQueue.shift() as Sound; var soundChannel:SoundChannel = currentSound.play(); // 监听播放完成事件,递归播放下一个 soundChannel.addEventListener(Event.SOUND_COMPLETE, function(e:Event):void { e.target.removeEventListener(Event.SOUND_COMPLETE, arguments.callee); playSoundSequence(soundQueue); }); }
3. 每帧只需要一行代码调用
现在不管哪一帧,你只需要在设置完题目和选项后,加这一行代码就能自动播放对应音效序列了:
stop(); QuestText.text = "0+2"; Button1.LabelText.text = "6"; Button2.LabelText.text = "2"; Button3.LabelText.text = "0"; // 就是这一行!自动解析+播放音效 playSoundSequence(getSoundQueueFromQuestion(QuestText.text));
这样一来,300多帧的重复工作就简化成了每帧加一行调用代码,再也不用重复写繁琐的事件监听啦。
内容的提问来源于stack exchange,提问作者Nareg
相关产品推荐
相关产品推荐

