播放的每种声音具有其自己的SoundChannel对象。SoundChannel对象控制声音的左和右回放声道的音量,并记录播放的进度。实际上,每个播放中的音乐对应一个SoundChannel对象,而不是Sound对象。Sound对象类似于声音的数据,可以同时产生同一个Sound对象的多个SoundChannel播放。当应用程序播放Sound对象时,将创建一个新的SoundChannel对象来控制回放。
下面的代码演示了如何利用SoundChannel对象追踪声音的播放进度:
var mysound:Sound=new Sound();
mysound.load(new URLRequest("sounddata/sample.mp3"));
mysound.addEventListener(Event.COMPLETE, onSoundLoaded);
var sdtf:TextField=new TextField;
var tff:TextFormat=new TextFormat();
tff.size=65;
tff.color=0x88FF66;
sdtf.defaultTextFormat=tff;
sdtf.text=" " , sdtf.width=150;
sdtf.x=100 , sdtf.y=65;
addChild(sdtf);
//创建定时器
var sndchecker:Timer=new Timer(500,0);
//添加定时器事件侦听
sndchecker.addEventListener(TimerEvent.TIMER,checkfunc)
var sndchannel:SoundChannel;
//侦听加载完成
function onSoundLoaded(event:Event):void
{
var localSound:Sound = event.target as Sound;
sndchannel=localSound.play();
sndchecker.start();
trace("load complete");
}
//侦听Timer事件
function checkfunc(eve:TimerEvent):void{
var sound_progress:uint=100*sndchannel.position/mysound.length;
sdtf.text=sound_progress+"%";
}
代码中利用一个事件定时器,不断的查询SoundChannel对象的位置。SoundChannel对象在调用Sound类的Play()方法时被自动创建和作为返回值提供。使用一个自定义的SoundChannel类型标识符接收这个返回值,以供后面的代码使用。
程序的运行效果请参考图所示:
在声音播放结束时,FlashPlayer会发送Event.COMPLETE消息,响应该消息,执行相应的删除和内存回复操作。