FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Home » Optimization »  Preloading .flv and .mp3 files with Flash

Preloading .flv and .mp3 files with Flash

by Charles Torvalds 12 comments

[hide]

Preload/Cache .mp3 .flv files with Flash ActionscriptThe company I work for does tons of online videos for our clients, and being the lead web designer I am responsible for making the videos work flawlessly and instantly. Fortunately for my clients, I am a little obsessive about finding the best of the best of the best way to do things. I have a LONG way to go, especially when it comes to flash, but here are a few choice tips and tricks that currently work for my clients.

You can read an alternate/older explanation of this method here.

Preloading files into Browser Cache

One thing I like to do that no-one can appreciate except me and maybe you is to preload the sites various .flv and .mp3 files into the site visitors cache. Let me give you an example. Site.com has 12 videos spread out on multiple pages, all are .flv files controlled by a single .swf flash video player. Most visitors arrive at the home page which has 1 of the 12 videos on it. So the trick is to preload the other 11 .flv video files from the home page. Then when the visitor goes to a different page with a different video, it loads instantly.

Preloading .flv files with Actionscript

The actionscript is easy, it opens a connection to the .flv file, sets the buffertime to 0, plays the video and immediately pauses, then seeks the position back to 0.

Its relatively easy to get this to work, heres all the actionscript you will need to preload any .flv file. Just create a new flash document, and on frame 1 enter in this actionscript. You can also search your flash help for "preloading" for more help.

var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
//attach videodisplay
_level0.attachVideo(ns);
ns.setBufferTime(0);
ns.play('http://static.askapache.com/f/flv/create-boot-ini.flv');
ns.pause();
ns.seek(0);

Preloading .mp3 files with Actionscript

This is even easier than .flv! This is all you need and the mp3 file will be requested from the browser and added to the browsers cache.

var songTrack:Sound = new Sound();
songTrack.loadSound("http://static.askapache.com/f/mp3/ga-urchin-speed.mp3", true);

Little Tricks and Tips

Passing filenames with flashvars

So now you have the actionscript and files, but what if you want to pass the file using flashvars? So /preloader.swf?file=http://static.askapache.com/f/flv/create-boot-ini.flv will work?

if (!_root.file) {
  file = 'http://static.askapache.com/f/flv/create-boot-ini.flv';
} else {
  file = _root.file;
}
 
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
//attach videodisplay
_level0.attachVideo(ns);
ns.setBufferTime(0);
ns.play(file);
ns.pause();
ns.seek(0);

Using javascript to time the downloads

Now, you may think you are a hotshot if you preload 12 .flv files from the homepage using swfobject or ufo, but the problem with doing that all at once is that flash has some real serious issues with running multiple instances like that. Meaning the movie that IS on your homepage might very well FREEZE or stutter mid-play if you are trying to preload all these files in the background. I won't get into advanced stuff here but to start with you should at least utilize something like a setTimeout function. I rely heavily on javascript loops to do this.

setTimeout(function(){swfobject or ufo code;},10000); // 10 second wait

Waiting till fully buffered

Depending on your .flv video player .swf, you may or may not have the capability to receive information on whether or not a file has been loaded or is fully buffered. So an additional step that I personally take is I don't start the preloading loop code until the 1st movie on the home-page has fully buffered. Sometimes I wait until its done playing.

Apache .htaccess

Of course, I can't forget this bit of .htaccess

AddType video/x-flv .flv
AddType application/x-shockwave-flash .swf
 
<filesMatch ".(flv|swf|mp3)$">
Header unset Pragma
FileETag None
Header unset ETag
Header unset P3P
Header set Cache-Control "public"
Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT"
</FilesMatch>

Feeling Lucky?

If by lucky you mean you dig learning how to make your sites FAST, heres some money.

Easy Apache Speed Tips Articles


August 5th, 2008

Comments Welcome

  • http://janoserdelyi.com janos erdelyi

    it would be a huge waste of bandwidth to *definitely* transfer many many bytes that will only *maybe* be accessed by a human if you were to scale this up to all sites taking this type of action.

    however, for end-user experience it's great when clicking around.

    what about a middle ground? download a certain sized byte-range as a buffer and then stream the rest out if they decide to watch/listen - that way they get an instant start, but fewer resources are used for things the end-user never clicked on.

  • Ken Luallen

    So you've covered flvs and mp3s... can you show us how to preload an xml's worth of jpgs / pngs? That would be magnificent!

  • Jessicca

    Hello,

    I've read your article on Preloading .flv files with Actionscript and have tried it out. It didn't work with my situation. I have a website intro with one video clip that should correspond to various text within my flash file. The easiest way to do this was by embedding the file, but then the sound quality was very poor. I then decided to go the progressive download route. I want to preload the file at the beginning of my swf file and then actually start playing it 195 frames into my swf file. Without being able to preload the file, my video is delayed the first time I visit the site but then catches up to where it should be by my third visit. Can you give me any advice?

    Thank you for your time,
    Jessicca

  • Alexander

    Hi. i found your post very useful. but i have a question. what happens if the user select one .flv that has not been completed yet. i have one swf that plays the video using the FLVPlayback object, but when i use it incorporating the code you posted the video doesn´t play. any suggestions?

  • Marco

    You are the man. Thank you so much for sharing these tips; these is actual useful information from someone doing actual useful work in the real world. Great read.

  • Leon Harris

    Thanks for this. It came is very useful as I am putting together an virtual Art gallery site, which is using a couple dozen FLV files to simulate moving around a Art Gallery. I needed a way to preload the videos before hand as they are all streamed for moving back and forward. I did a quick alteration to your code so that it would load multiple videos one after the other from an array.

    video = new Array();
    video[1]="intro1.flv";
    video[2]="move1.flv";
    video[3]="move2.flv";
    video[4]="intro2.flv";
    video[5]="move1a.flv";
    video[6]="move2a.flv";
     
    if(i ==undefined){_global.i = 1;}
     
    file = 'clips_400kbps/'+video[i];
     
    var nc:NetConnection = new NetConnection();
    nc.connect(null);
    var ns:NetStream = new NetStream(nc);
    //attach videodisplay
    _level0.attachVideo(ns);
    ns.setBufferTime(0);
    //myVideo.attachVideo(ns);
    ns.play(file);
    ns.pause();
    ns.seek(0);
     
    ns.onStatus = function(infoObject:Object) {
    if(infoObject.code=="NetStream.Buffer.Flush"){
    if(i < video.length-1){
    i++;
    play();
    }else{
    trace("videos have all been preloaded");
    stop();}}}

    I probably could refine this more but it did what I needed.

    Cheers.

  • Lucho

    How the heck do I turn off this awful music you have on this page?! Damn! are we back in the 90's?

    BTW, thanks a lot for this post :P

  • Luke

    So how do I then access the flv? The code looks like it's working right- Safari's activity monitor shows that my flv is loading- but then when I go to play the flv, the activity monitor shows that it's opening up another stream for the same file.

  • Kev Man

    Preloading FLV with AS3....DOES NOT WORK!!!

    Its relatively easy to get this to work, heres all the actionscript you will need to preload any .flv file. Just create a new flash document, and on frame 1 enter in this actionscript. You can also search your flash help for “preloading” for more help.

    No. Actually i copied and pasted this (as well as about 20 other so far today that boasted it was super simple) and i get error messages. As far as searching preloading in the Flash help, HA!!!! Good luck getting any information that you can use unless you are very familiar with AS, which im not and which is why im looking for copy and paste code, which Adobe has done a very good job of making this extremely difficult.

  • http://www.ahrooga.com/ Will Dady

    Personally I am very much against pre-caching content like this. Purely for the fact that it is a waste of a user's bandwidth and you can't assume a user will watch all 12 videos. I would attempt to intelligently predict what video a user is likely to watch next and pre-cache only that one. Obviously that would only work if your videos followed some kind of sequential order :

  • Mark Corkins

    Thanks for the tutorial on preloading. I needed this to preload the next series of training videos while the user is watching the first one. There are ten in all and some are quite large. Thanks!

  • abc

    Hi, this all was for .flv files but what about .wmv files?????????

My Online Tools

Related Articles
Twitter


My Picks
Newest Posts

WordPress Development
Hacking and Hackers

The use of "hacker" to mean "security breaker" is a confusion on the part of the mass media. We hackers refuse to recognize that meaning, and continue using the word to mean someone who loves to program, someone who enjoys playful cleverness, or the combination of the two. See my article, On Hacking.
-- Richard M. Stallman






It's very simple - you read the protocol and write the code. -Bill Joy

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 License, just credit with a link.
This site is not supported or endorsed by The Apache Software Foundation (ASF). All software and documentation produced by The ASF is licensed. "Apache" is a trademark of The ASF. NCSA HTTPd.
UNIX ® is a registered Trademark of The Open Group. POSIX ® is a registered Trademark of The IEEE.

Site Map | Contact Webmaster | License and Disclaimer | Terms of Service

↑ TOPMain