Last year, unobtrusive javascript really hit the scene and my sites no exception. I’ve been perfecting the technique to show an mp3 audio player, which I have debuted at radio6.nl this week. It’s a tiny bit of Javascript with a big help from jQuery.
Basically what you want is to create an mp3 player on the fly, instead of embedding this with an OBJECT tag. This keeps the page very light to load. It also makes sure that older browsers and mobile devices still see the regular mp3 file, so they can download it and play in some other way. It’s also great for search engines since it keeps all the markup semantic, and adds behaviour on top of that. Just like Tim Berners-Lee intended!
Last year I would probably have used things like swfobject or the Anarchy player. But there is no reason not to solve this in jQuery directly. All it takes is this little bit of javascript:
// replace all links to mp3 files with a flash player
$("a[href$='.mp3']").each(function(){
var href = $(this).attr('href');
var player = '<div class="player"><object type="application/x-shockwave-flash" data="'+Site.Config.theme_url+'/flash/player_mp3_maxi.swf" width="200" height="20"> \
<param name="movie" value="'+Site.Config.theme_url+'/flash/player_mp3_maxi.swf" /> \
<param name="FlashVars" value="mp3='+href+'" /> \
</object><p>'+$(this).html()+'</p></div>';
$(this).replaceWith(player);
});
Naturally this would be inside the document ready event.
Site.Config is just top-level hash that holds various functions related to the application. And I found the MP3 player here, it’s tiny and fast and even customizable, perfect for my needs.