Page 1 of 1

Embedding short MP3 files on a web page

Posted: Wed Oct 07, 2009 12:40 pm
by JamesMayor
I need to embed short MP3 files onto a Web page such that when the user clicks on a link the MP3 will play. As these are short files I do not want to stream them from the server. How can this be coded in a page such that it will play via either a browser plugin or via a player installed on the user's pc.

Re: Embedding short MP3 files on a web page

Posted: Mon Oct 19, 2009 5:21 pm
by Hany
Hi James,

I've done a little bit of research and found that you can use the script tag in HTML to accomplish what you need. However, using the approach you requested requires the user to have some sort of browser plugin/player installed (Quicktime, realplayer, etc.)

Here is a sample code:

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function play(source)
{
  var mp3 = document.getElementById("sounds");
  if(!mp3)
  {
     mp3 = document.createElement("embed");
     mp3.id = "sounds";
     mp3.src = source;
     mp3.setAttribute("hidden", "true");
     document.body.appendChild(mp3); 
  }
  else
  {
     document.body.removeChild(mp3);
     mp3 = document.createElement("embed");
     mp3.id = "sounds";
     mp3.src = source;
     mp3.setAttribute("hidden", "true");
     document.body.appendChild(mp3);
  }    
}

</script>
  <title></title>
</head>

<body>
  <p><a href="javascript: play('/Music_1.mp3')">Music 1</a></p>
  <p><a href="javascript: play('/Music_2.mp3')">Music 2</a></p>       
  <p><a href="javascript: play('/Music_3.mp3')">Music 3</a></p>       
</body>
</html>

I added a JavaScript function (play) that attaches a new embed tag to the document with the source pointing to the mp3 file. I'm also checking if the file already exists by looking for the same id ("sounds"), then remove it from the document and then recreate it. You might be thinking, why didn't I just change the source to point to the next mp3 file. Unfortunately, browsers do not always behave the same. This was basically needed for browser compatibility.

Please let me know if this works or if you need further help.

Thanks,

Hany