Partial preloading video with as3

David Jones
@david3jones
avatar-davidejones

I recently had to revisite a website i made that had a variation of videos on it. These videos were just loaded straight from the server, the client complained that it took far to long to start to play the videos and that it needed to show that something was happening.

In the end the solution i came up with was to just preload 1mb of the video showing a preloader and then to start playing the movie. Then as the movie is playing it should hopefully stream the rest pretty easily.

In order to do this i used the following code:

private var loader:URLLoader = new URLLoader();
private var dispatched:Boolean = false;
var myContent:URLRequest = new URLRequest("flash/"+flv);
loader.addEventListener( Event.COMPLETE, loadComplete );
loader.addEventListener( ProgressEvent.PROGRESS, handleProgress );
loader.load( myContent );
//add progress bar to stage code here
private function handleProgress(event:ProgressEvent):void {
    	var loaded:Number = Math.round(event.bytesLoaded);
    	var total:Number = Math.round(event.bytesTotal);
    	var percent:Number = loaded/total*100;
    	//i only want it to preload 1mb
    	var newtotal:Number = 1000000;
    	var newpercent:Number = loaded/newtotal*100;
    	if((loaded >= newtotal) && (dispatched == false)) {
    		loader.dispatchEvent(new Event(Event.COMPLETE));
    		dispatched = true;
    		abortLoader();
    	}
    	trace(Math.round(newpercent) + " %");
    	//increase progress bar percentage code here to newperecent
}
private function abortLoader(){
    	dispatched = false;
    	try {
    		loader.close();
    	} catch(error:Error) {}
}
private function loadComplete(event:Event):void {
    	//remove progress bar code here
    	//set video to play what we have so far and stream the rest
    	videoConnection = new NetConnection();
    	videoConnection.connect(null);
    	videoStream = new NetStream(videoConnection);
    	videoStream.bufferTime = 5;
    	video = new Video(352.9, 276.4);
    	video.name = "video";
    	videoStream.play(flv);
}

Comments

    Comments are currently closed