O'Reilly    
 Published on O'Reilly (http://oreilly.com/)
 See this if you're having trouble printing code examples


Several years ago, I wanted a better way to present the MP3 examples I produce for my gear reviews, so I started exploring JavaScript. Before long, I discovered how to make audio links play back in a handy pop-up window, complete with volume and transport controls. All it took was adding a smidgen of JavaScript to a standard audio link and uploading a small JavaScript file.

That humble hack led to one of our most popular articles, "Build a Simple MP3 Player for Your Site." Hundreds of people wrote in to suggest new features, and we responded with articles on adding images, m3u playlist support, and wider compatibility to the players. But the requests kept pouring in, so I thought I'd share some of my latest experiments and discoveries while I continue to refine the player.



Click the links below to jump to a specific experiment.

  1. Pop-up Link Generator
  2. Random Sound on Load
  3. Inline Embedded Player


Pfeiffer pop-up

Reader Tommy Detamore customized the pop-up player with a wood-grain background and plugin-dependent height for guitarist Chris Pfeiffer's site. Note the ActiveX warning in the Internet Explorer screenshot at bottom. I'm still experimenting with workarounds for that.

1. Pop-up Link Generator

One nice feature of the original article was that it included a downloadable Dreamweaver extension that let you create the special links just by filling out a form. But not everyone has Dreamweaver, and the extension doesn't work with the latest version of the script. So I made a Web form to generate the links instead. As a side benefit, developing the form taught me some new JavaScript techniques such as form validation. One of the most common mistakes readers made was adding raw apostrophes to song titles, which broke the script. (See the Lab Safety sidebar.) View this page's source code to see the script, which I've commented heavily.

Here's how to use the form. (I've filled in an audio file address so you can try it out. The sound is from Peter Drescher's article "Singing With Your Thumbs: How To Make User Interfaces Musical.")

  1. Upload the external script called BatmoAudioPop.js to your site. The script is available on this page. (For this demo, I've embedded the script rather than linking to it.)
  2. Create a link to the script in your page, like this:
    <script type="text/javascript" src="BatmoAudioPop.js"></script>
  3. Upload your media file (MP3, AIF, WAV, MID, etc.).
  4. Use the following form to generate a special link to the file that will create a pop-up media player when clicked.
  5. Copy the link and paste it into your page.
Link Text: Pop-Up Title:
File Path:
File Size (optional): KB MB
File ID:   (Assigning the same value to all links on a page will make them open in the same pop-up.)

Lab Safety: Common Mistakes

Two common errors people make when implementing this script include omitting the link to the external JavaScript file and not "escaping" apostrophes or other non-alphanumeric characters in song titles. (Raw apostrophes will break the script, so you need to precede them with backslashes.)

If you're getting both a normal window and a pop-up when you click the link, it probably means you've omitted the return false part of the link. It's designed to make the browser fire only the JavaScript section of the link, not the href= section. (That section should fire only when JavaScript is disabled.) Similarly, if clicking an MP3 link opens a new window rather than a pop-up, it means that JavaScript is either disabled in the browser or that the browser can't find the external file.

2. Random Sound on Page Load

One frequent reader request was for a way to play a random sound file when the page loads. Here's a simple approach I discovered at 24fun.com and subsequently used at BambooSoul.com, a site I designed for a shakuhachi player. So that you can focus on the randomization section, I'm using the simplest possible embedding code. There's a more complete approach at Scriptwell.net, and many programmers use the <object> tag as well, as shown in Experiment 1.

<script type="text/javascript">
<!-- Hide script from old browsers
var Waves=new Array("sound1.mp3","sound2.mp3","sound3.mp3","sound4.mp3","sound5.mp3");
var WavePath="http://downloads.oreilly.com/digitalmedia/2007/06/"; // If your files are in another directory, such as "sounds/", put that path here.
var WaveNumber=Math.floor((Waves.length)*Math.random());
var DisplayNumber = WaveNumber*1+1; // multiply to ensure items are numbers
document.write("<h2>Item "+ DisplayNumber +"<\/h2>(<a href='http://digitalmedia.oreilly.com/examples/oreilly/digitalmedia/2007/06/randosound.html'>Refresh</a> to hear a new sound.)");
document.write("<embed src='" + WavePath + Waves[WaveNumber] + "' autostart='true' loop='false' width='2' height='2' hidden='true'>");
document.write("</embed>");
// Stop hiding script -->
</script>

Try it (a pop-up window will open). The voice is from the Cepstral speech synthesizer. I made the music in Ableton Live.

3. Inline Player

One of my longterm goals is to learn enough JavaScript to make my own version of the Del.icio.us PlayTagger. This slick bookmarklet inserts a tiny Play/Stop button in front of MP3 links on almost any site you visit. Unlike my pop-up player, though, Playtagger supports only the MP3 format, and it lacks a position slider and volume control.

So my latest experiment is to encode MP3 links so they spawn a player bar next to themselves rather than in a pop-up. Again, I've simplified the embedding code for clarity. I also want to find a way to replace the current playback controls when someone clicks a link a second time. (Currently, the controls stack up, which is somewhat entertaining.)

Click these audio links to see the effect. Notice how the player width can be set on a link-by-link basis. These clips are from our interview with producer/remixer Carmen Rizzo.

White Flag (remix)

Dunya (short controller bar)

Here's the code. The links take the form <a href="songfile.mp3" target="_blank" id="example1" onclick="javascript:playBtn(this.id,this.href,'100');return false">Click here</a>, in which each has a unique ID and triggers the playBtn JavaScript when clicked.


<script type="text/javascript">
// Embed a media player before a link when the link is clicked
function playBtn(linkID,filePath,playerWidth) {
if (!playerWidth || playerWidth<34){
playerWidth=34;
}
var oneSpace = document.createTextNode(" ")
// To do: Create an outer object called iePlayer with Internet Explorer parameters, then add tinyPlayer as a child.
var tinyPlayer = document.createElement("embed");
tinyPlayer.setAttribute("width",playerWidth);
tinyPlayer.setAttribute("height","16");
tinyPlayer.setAttribute("type","audio/mpeg");
tinyPlayer.setAttribute("src",filePath);
tinyPlayer.setAttribute("kioskmode","true");
var triggerLink = document.getElementById(linkID);
// To do: Remove player if it already exists (because the user clicked the link twice)
triggerLink.parentNode.insertBefore(tinyPlayer,triggerLink);
triggerLink.parentNode.insertBefore(oneSpace,triggerLink);
}
</script>

Onward

That's all we have space for now, but there's a lot more bubbling in the lab. I'll share some interesting video-embedding tricks in a future article. Please leave comments below if you have suggestions or questions.

David Battino is the audio editor for O’Reilly’s Digital Media site, the co-author of The Art of Digital Music, and on the steering committee for the Interactive Audio Special Interest Group (IASIG). He also writes, publishes, and performs Japanese kamishibai storycards.


Return to digitalmedia.oreilly.com.

Copyright © 2009 O'Reilly Media, Inc.