最近帮公司做flash,要求flash里播放视频,采用的是flash播放外部flv视频的方式。为了能够在播放的时候有顺利流畅的效果,所以事先把所要播放的flv文件全部先预加载,加载完毕后再开始播放。其部分主要action script类似如下,在flash里新建视频元件,然后用netstream控制flv的播放,其方法bytesLoaded、bytesTotal可用作计算预加载的进度统计,progressBar显示loading条。如果服务器不支持flv文件,将flv改为swf类型便可。
stop();
my_nc = new NetConnection();
my_nc.connect(null);
my_ns = new NetStream(my_nc);
Finance.attachVideo(my_ns);
my_ns.play("Finance.swf");
my_nc3 = new NetConnection();
my_nc3.connect(null);
my_ns3= new NetStream(my_nc3);
ns3.attachVideo(my_ns3);
my_ns3.play("3.swf");
this.createTextField("loaded_txt", this.getNextHighestDepth(), 10, 10,
160, 22);
this.createEmptyMovieClip("progressBar_mc", this.getNextHighestDepth());
progressBar_mc.createEmptyMovieClip("bar_mc",
progressBar_mc.getNextHighestDepth());
with (progressBar_mc.bar_mc) {
beginFill(0xFF0000);
moveTo(0, 0);
lineTo(100, 0);
lineTo(100, 10);
lineTo(0, 10);
lineTo(0, 0);
endFill();
_xscale = 0;
}
progressBar_mc.createEmptyMovieClip("stroke_mc",
progressBar_mc.getNextHighestDepth());
with (progressBar_mc.stroke_mc) {
lineStyle(0, 0x000000);
moveTo(0, 0);
lineTo(100, 0);
lineTo(100, 10);
lineTo(0, 10);
lineTo(0, 0);
}
var loaded_interval:Number = setInterval(checkBytesLoaded, 500,
my_ns,my_ns3);
function checkBytesLoaded(my_ns:NetStream) {
var pctLoaded:Number = Math.round(my_ns.bytesLoaded / my_ns.bytesTotal
* 100);
loaded_txt.text = Math.round(my_ns.bytesLoaded / 1000 + my_ns3.bytesLoaded / 1000) + " of " +
Math.round(my_ns.bytesTotal / 1000 + my_ns3.bytesTotal / 1000) + " KB loaded (" + pctLoaded +
"%)";
progressBar_mc.bar_mc._xscale = pctLoaded;
if (pctLoaded>=100) {
loaded_txt._visible=false;
progressBar_mc._visible=false;
clearInterval(loaded_interval);
play();
}else{
stop();
}
}