15.9.跟踪音乐播放进度

问题
我想知道当前播放的歌曲已经播放到什么位置了
解决办法
使用Sound.length得到歌曲的总长度,SoundChannel.position得到当前的播放位置
讨论
第15.6章讨论了如何添加一个进度条既显示音乐的播放进度,也显示音乐的下载进度,这一节就来创建播放进度条。

这一节涉及如何跟踪音乐的播放进度,要做到这一点,必须知道两件事:音乐的长度和当前的播放位置。这两个属性分别在两不同的类里。长度属性在sound类里,播放位置在SoundChannel类里,和缓冲条一样,这两个值相除就是播放进度百分比。

但这里有点比缓冲条复杂,问题就是length属性值,它是不确定的,直到声音被下载完才确定,也就说它只表示已经被下载的那部分数据的长度,举个例子说,如果一个10分钟的音乐已下载了10%,那么length报告歌曲长度为1分钟(length和position的单位都是毫秒)

还好,只通过简单的数学算法就可得出声音文件的真实长度,只要长度除以缓冲百分比即可算出实际长度。那上一个例子说,1除以1/10等于10,得到声音的长度为10分钟。

缓冲百分比就是bytesLoaded/bytesTotal,所以长度的计算公式就是:
+展开
-ActionScript
length /= percentBuffered;

下面的例子显示两个进度条:
+展开
-ActionScript
package {
import flash.display.Sprite;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.URLRequest;
import flash.events.Event;
public class ProgressBar2 extends Sprite {
private var _sound:Sound;
private var _channel:SoundChannel;
public function ProgressBar2( ) {
addEventListener(Event.ENTER_FRAME, onEnterFrame);
_sound = new Sound(new URLRequest("song.mp3"));
_channel = _sound.play( );
}
public function onEnterFrame(event:Event):void
{
var barWidth:int = 200;
var barHeight:int = 5;
var loaded:int = _sound.bytesLoaded;
var total:int = _sound.bytesTotal;
var length:int = _sound.length;
var position:int = _channel.position;
// Draw a background bar
graphics.clear( );
graphics.beginFill(0xFFFFFF);
graphics.drawRect(10, 10, barWidth, barHeight);
graphics.endFill( );
if(total > 0) {
// The percent of the sound that has loaded
var percentBuffered:Number = loaded / total;
// Draw a bar that represents the percent of
// the sound that has loaded
graphics.beginFill(0xCCCCCC);
graphics.drawRect(10, 10,
barWidth * percentBuffered,
barHeight);
graphics.endFill( );
// Correct the sound length calculation
length /= percentBuffered;
// The percent of the sound that has played
var percentPlayed:Number = position / length;
// Draw a bar that represents the percent of
// the sound that has played
graphics.beginFill(0x666666);
graphics.drawRect(10, 10,
barWidth * percentPlayed,
barHeight);
graphics.endFill( );
}
}
}
}

加支付宝好友偷能量挖...


评论(0)网络
阅读(91)喜欢(0)flash/flex/fcs/AIR