Cool Javascript MP3 Song Playback in Web Page with Custom Controls

Created: October 12, 2007
Last Edited: August 18, 2011
Subscribe to Internet Tips and Tools Feed
f Share
G+ Share
in Share
P in it

: Off



  • New as of 7/12/2008: Added Shuffle button.
  • Javascript .mp3 and .mid player in Internet Explorer, Netscape, Mozilla Firefox, Safari and Opera.
  • Instead of using default windows media player controls or default Quicktime controls, you can make your own custom controls.
  • Easily create a playlist of MP3 music files.
  • Full Play, Stop, Pause, Rewind, Fast-Forward, Volume, Previous Song, Next Song and Fade Out controls for most browsers including IE 6.0+, Netscape 7.1+, Firefox 1.5+ and Opera 9+.
  • Play, Stop, Previous Song and Next Song controls for Safari and other older browser versions.
  • Automatic playback of next song in playlist in most browsers

How to Use

  1. Right click on sound.js and save it to your hard drive.
  2. Copy the following textbox and paste it just before </HEAD> in your HTML document:
  3. Copy the following textbox which contains the player controls which can be customized and paste it in the body of your HTML document where you want the player controls to appear:
  4. For the Playlist make an invisible textarea in the BODY of your HTML document like the one below with each mp3 listed on a seperate line. Make sure the textarea has the id songlist:
  5. or an easier way to make the playlist is to right click on the following batch file and save it to your hard drive in the folder that contains the mp3 and mid files you want in the playlist: songs.bat
    It will create a file called songs.txt which will contain the textarea element along with all your songs. Then paste the information from songs.txt into the body of your HTML document.
  6. If you are putting your songs in a different folder from your INDEX.HTML file then edit sound.js and change the folder variable from var folder = ''; to var folder = 'music/'; where music is the name of the folder that holds the mp3 files.

How it Works


songs.bat contents looks like the following:

You can edit the batch file if you wish. The important line is:

dir /b /od *.mp3 *.mid >> %filename%
There you can add more file types if you wish. It basically uses the dir command in basic listing mode /b and orders the list by date /od. You can change the sort method to order by name (alphabetic) by replacing /od with /on. See the dir command help for more options. (Click on Start -> Run. Type in cmd and press ENTER. Type in dir /? and press ENTER.)

Note: Windows Media Player will play .WMA files, but Quicktime Player (which Firefox, Safari and Opera uses), will NOT play .WMA files.

Quicktime vs. Windows Media Player

These Javascript functions use Windows Media Player for Internet Explorer and Netscape, but use Quicktime for Firefox, Safari, and Opera. Here are the reasons:

  • Internet Explorer: Since Internet Explorer and Windows Media Player are both made by Microsoft I thought it fitting to use Windows Media Player. However, Internet Explorer 6.0 and above seems to have full control over Quicktime as well as Windows Media Player in the browser.
  • Netscape: The Netscape browser does not seem to allow you to control Quicktime with Javascript controls such as document.embeds['sound'].Play(); therefore I used Windows Media Player because Netscape can control it with Javascript.
  • Firefox: Firefox 1.5 can't control Windows Media Player with Javascript, but it can control Quicktime.
  • Safari: The Safari browser can't seem to control Windows Media Player or Quicktime with Javascript. Go figure, since Quicktime and Safari are both made by Apple. Since Quicktime is made by Apple I decided that I would use that player.
  • Opera: Opera can control Quicktime with Javascript but it cannot control Windows Media Player.

Off Screen DIV

If we were to create an invisible DIV then the contents of the DIV can't be played and therefore don't work. Also in many browsers, for some reason we don't have access to Javascript media player controls if we tell the media player to make itself invisible. So to solve both of these problems and to not display either the Quicktime or Windows Media Player default players we just place them off screen by creating an offscreen DIV to hold the player as follows:

// Make a DIV to hold the player and place it off the screen
// so that we don't see it
document.write('<DIV ID="player"'
+ 'style="position:absolute;left:-1000;top:-1000"'
+ '></DIV>');

Detect Browser

To detect the browser so we can put the correct media player in the player DIV we use the following function:

function detect_browser()
var browser_name = navigator.userAgent;
// We have to check for Opera first because
// at the beginning of the userAgent variable
// Opera claims it is MSIE.

if (browser_name.indexOf("Opera")!= -1)
browser_name = "Opera";
else if (browser_name.indexOf("Firefox")!= -1)
browser_name = "Firefox";
else if (browser_name.indexOf("MSIE")!= -1)
browser_name = "MSIE";
else if (browser_name.indexOf("Netscape")!= -1)
browser_name = "Netscape";
else if (browser_name.indexOf("Safari")!= -1)
browser_name = "Safari";

return browser_name;

} // end function detect_browser()

Load A Song

Then we use the following function to create the player and load the song:

function load(media)
var player = document.getElementById('player');

if (detect_browser() == "MSIE" ||
detect_browser() == "Netscape")
player.innerHTML = '<object id="sound"'
+ 'classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6"'
+ 'codebase=",1,52,701"'
+ 'standby="Loading Microsoft® Windows® Media Player components..."'
+ 'type="application/x-oleobject" width="160" height="144">'
+ '<param name="url" value="'+media+'">'
+ '<param name="volume" value="100">'
+ '<embed id="sound" type="application/x-mplayer2" src="'+media+'"'
+ 'classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6"'
+ 'pluginspage=""'
+ 'type="application/x-mplayer2"'
+ 'url="'+media+'"'
+ 'voume="100"'
+ 'width="160" height="144">'
+ '<\/embed>'
+ '<\/object>';
else // if Safari or Firefox, then load Quicktime controls
player.innerHTML = '<OBJECT '
+ 'CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" '
+ 'WIDTH="160"HEIGHT="144" ID="sound"'
+ 'style="position:absolute;left:-1000;top:-1000"'
+ 'CODEBASE="">'
+ '<PARAM name="SRC" VALUE="'+media+'">'
+ '<PARAM name="AUTOPLAY" VALUE="true">'
+ '<PARAM name="CONTROLLER" VALUE="false">'
+ '<PARAM name="VOLUME" VALUE="100">'
+ '<PARAM name="TYPE" VALUE="audio/wav">'
+ '<embed classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"'
+ 'name="sound"'
+ 'id="sound"'
+ 'src="'+media+'"'
+ 'pluginspage=""'
+ 'volume="100"'
+ 'enablejavascript="true" '
+ 'type="audio/wav" '
+ 'height="16" '
+ 'width="200"'
+ 'style="position:absolute;left:-1000;top:-1000"'
+ 'autostart="true"'
+ '> </embed>'
+ '</OBJECT>';

} // end function load(media)

Object tag

The object tag has the following properties to specify which player to use: CLASSID, CODEBASE, STANDBY and TYPE.

CLASSID="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" specifies windows media player 7 or later.

CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" specifies Quicktime.

CODEBASE=",1,52,701" specifies where to download the activex control for windows media player for the browser if they do not have it.

CODEBASE="" specifies where to download the activex control for the quicktime player for the browser if they do not have it.

STANDBY="Loading Microsoft® Windows® Media Player components..." specifies the text to write to the screen while the media player control is being downloaded.

TYPE="application/x-oleobject" specifies that we are loading a Windows Media player activex object.

<PARAM name="TYPE" VALUE="audio/wav"> specifies that we are loading audio wav or mp3 files for quicktime. (Note: Windows Media Player will support .WMA audio files, but Quicktime will not play .WMA audio files.)

Embed tag

The embed tag has the following properties to specify which player to use: CLASSID, TYPE and PLUGINSPAGE.

CLASSID="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" specifies windows media player 7 or later.

CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" specifies Quicktime.

pluginspage="" specifies where they can download Windows Media Player if they do not have it.

pluginspage="" specifies where they can download Quicktime if they do not have it.

type="application/x-mplayer2" tells the browser we are loading windows media player activex controls.

type="audio/wav" tells the browser we are loading wav or mp3 files with quicktime.

To support Safari and older versions of browsers that don't support the control of media players in the browser using Javascript we have included the commands to autostart the song. The function load(media) is called when the user presses the Play button.

Javascript Controls


In order to control quicktime with Javascript, the following must be included in the embed statement:


Also notice that we have included both ID="sound" and NAME="sound" for the Quicktime player embed statement. If we only had the ID="sound" identifier then we would still be able to control the Quicktime Player by using document.embeds['sound']. We could use functions such as the following to control the music:

document.embeds['sound'].Stop(); // Pause
document.embeds['sound'].Play(); // Play
document.embeds['sound'].GetVolume(); // Get Volume Level
document.embeds['sound'].SetVolume(x); // Set Volume from 0 to 256(loudest)
document.embeds['sound'].GetTime(); // Get Current Time in song
document.embeds['sound'].GetDuration(); // Get Duration of song
document.embeds['sound'].GetTimeScale(); // Get TimeScale

(NOTE: The time scale of Quicktime songs is not always in seconds. To convert the current time and current duration of the song to minutes:seconds, here is the formula:

time = document.embeds['sound'].GetTime();
duration = document.embeds['sound'].GetDuration();
scale = document.embeds['sound'].GetTimeScale();
time = Math.floor(time*(1/scale)); // convert to seconds
duration = Math.floor(duration*(1/scale)); // converts to seconds
// convert seconds into mm:ss
mins = Math.floor(time / 60);
secs = time - (mins * 60);
time = mins + ':' + secs;
mins = Math.floor(duration / 60);
secs = duration - (mins * 60);
duration = mins + ':' + secs;

Since we also include NAME="sound" in the Quicktime embed statement, we are also able to control the player with document.sound. We could use functions such as the following to control the music:

document.sound.Stop(); // Pause
document.sound.Play(); // Play
document.sound.GetVolume(); // Get Volume Level
document.sound.SetVolume(x); // Set Volume from 0 to 256(loudest)

For a complete list of Quicktime Javascript Controls go to:

MP3 ID3 Tag info

Quicktime includes a way to get the artist name and song title from the MP3 ID3 tag using javascript:

song_title = document.sound.GetUserData('©nam');
song_artist = document.sound.GetUserData('©ART');

At first I thought these functions did not work because they kept returning null. I finally realized that they did work but I was calling them too quickly after loading the song. Quicktime has to load most of the mp3 music file before it can tell you the ID3 tag information. So now the display_info() function in sound.js calls itself again if the above functions return null:

song_title = document.sound.GetUserData('©nam');
song_artist = document.sound.GetUserData('©ART');
/* Quicktime has a problem of not being able to load
the song name and artist until most of the song is
loaded, so if song_title == null we need to call this
function again in a few milliseconds */
if (song_title == null)
setTimeout('display_info();', 250);

Windows Media Player

Windows Media Player 7 and later is controlled from javascript with document.sound.controls and document.sound.settings and So we have access to functions such as the following:

document.sound.controls.stop(); // Stop; // Play
document.sound.controls.pause(); // Pause
document.sound.settings.volume; // Get volume level
document.sound.settings.volume = x; // Set volume from 0 to 100 (loudest); // Buffering Progress from 0 to 100
document.sound.playState; // Play state of current song
document.sound.controls.currentPositionString; // Current position in minutes:seconds
document.sound.currentMedia.durationString; // Duration of song in minutes:seconds

MP3 ID3 Tag Info

Windows Media Player also includes javascript functions to get the song title and song artist from the MP3 ID3 Tag:

song_title = document.sound.currentMedia.getItemInfo('Title');
song_artist = document.sound.currentMedia.getItemInfo('Author');

For a complete list of Windows Media Player Javascript controls go to:

Also go to:
Media Player Controls Object
Media Player Media Object
Media Player Network Object
Media Player Settings Object

Back to
Subscribe to Internet Tips and Tools Feed        

User Comments

There are 89 comments.

Displaying first 30 comments.

1. Posted By: tvradio - - April 10, 2008, 3:17 pm
Thank you for the code of cool mp3 player.

With a little modification, we can listen a list mp3 of esnips using your coolmp3 player.
Here is an example i made:

( A little problem is that is starts play from 2nd song
and then, by using the NextSong button. Then it plays normaly)
About embed media-player in firefox without using quicktime, here is a solution i have use in my webpage:
i use:
that plays mp3 using: playmedia(times,height,width,"songname")
If it is possible, please remake your sound.js to be compatible with firefox, without using quicktime.
Thanks again.
Koltsidas Michael

2. Posted By: tvradio - - April 12, 2008, 1:40 pm
Good job, Thank you.
I experimented with your javaplayer. It plays only in internet explorer.

I tried and made a firefox-javaplayer that plays a list of esnips-songs.(

My player can be found at

It has an array of 300 song-IDs from esnips, then adds the time-function to allow direct playing songs in mediaplayer, reading from esnips. I know about nothing for java, but i try it.

If anybody wants, he can improve it. You can use free my code.

Koltsidas Michael
(newby in java)

3. Posted By: True_mesiash - - May 4, 2008, 7:50 am
I'm trying to use this script on my ActiveDesktop. And I'm getting error that looks something like this:

"There was error in the script on this page
Line: 1
Sign: 1
Error: Object expected
Code: 0

URL: file//

Do you want to continue using scripts on this page?

[translation from my native language]

In the Script I've removed parts that show ID3 Tag and time. [there were errors there]

Java scripts are not my strong side.
Please help.

using IE7 but i think Active desktop might still use IE6.

4. Posted By: prachi - - May 13, 2008, 4:21 am
Good work..It has helped a lot for developing my own jukebox. But, the problem I find in this is that it does not play songs continously. i.e one after another..If possible, please help in doing that

5. Posted By: ranjeet - - July 10, 2008, 2:52 pm
I checked above code, it played only one song and stopped , it does not go automatically, i was looking player, which play online mp3 song automatically and randomly like offline radio.

Please please help for this issue please.

my email address is :

6. Posted By: Ross - - September 3, 2008, 4:27 am
Have to say huge thanks! This is exactly what I was looking for and testing for me so far in firefox has worked to perfection. Great job.

7. Posted By: ameet topare - - September 8, 2008, 5:41 am
i am getting the value of sound as 0 using document.embeds['sound'].GetVolume(); or

8. Posted By: Josh - - September 26, 2008, 2:09 pm
I tried to use the code in an aspx page, and added the tags to the page. When viewing the page in Firefox it plays the song for about a second, and then stops. any help on this would be much appreciated. Thanks.

9. Posted By: Josh - - September 26, 2008, 2:11 pm
I tried to use the code in an aspx page, and added the "form" tags to the page. When viewing the page in Firefox it plays the song for about a second, and then stops. any help on this would be much appreciated. Thanks.

10. Posted By: kl - - November 17, 2008, 10:39 am
is there any way to hide the player and just have the buttons?

11. Posted By: KL - - November 17, 2008, 11:06 am
nevermind, figured out if you add the dimensions in the sound.js file to width="0" height="0" nothing shows up. Not sure how this is cross browser.

But I also have a second question. Is there a way to just have one button that when you click it plays and when you click again, it stops playing?

view here what i'm trying to do...

12. Posted By: Jeff - - November 17, 2008, 5:59 pm
Change the play_song() function in sound.js to the function below and then the Play button will become both a play button and a stop button:

function play_song()
// Check to see if current song has stopped
if (document.getElementById('player').innerHTML == '')
setTimeout('display_time();', 1000);
setTimeout('display_info();', 1000);
document.getElementById('play_btn').innerHTML = "Stop";
else // otherwise stop it and change button text
document.getElementById('play_btn').innerHTML = "Play";
} // end function play


13. Posted By: amadzay - - November 27, 2008, 9:40 am
how is it possibile, if the song1 in page1 is finished it goes automatically to page2 and plays song2 and so on..


14. Posted By: Jeff - - November 28, 2008, 11:53 am
The answer is in the function display_time()

Look toward the bottom of display_time() function and change:

// This is for Firefox
if (time == duration) // if at end of song
next_song(2); // then play next song in playlist
// This is for Ie
if (song_status == 1) // song stopped

to sommething like:

// This is for Firefox
if (time == duration) // if at end of song
window.location = ''; // then load next page
// This is for Ie
if (song_status == 1) // song stopped
window.location = ''; // then load next page

Then on page 2 instead of waiting for a play button to be pressed, you could call the play_song() function from the very bottom of the function loadsongs()


15. Posted By: Ekix - - December 2, 2008, 3:54 pm
Hello guys,

Sorry I'm a bit lost, so could someone give me an example of a working web page using this javascript system.

I'm a bit confused how to do it, anyway I'd like to get my player to show the player also and a drop down to choose what the visitor wants to select selects to play.

At the moment I'm using embedded Windows Media player in my web pahe, but it only works

If anyone could help me a bit, that would be nice...


16. Posted By: Ahmad - - December 22, 2008, 1:13 am
Thanks a lot for your script.
I have changed window.onload = loadsongs; to window.onload = play_song; but the player can not find the soundfile but with function loadsongs work well.
Demo at

17. Posted By: Ahmad - - December 23, 2008, 6:08 am
by luck I have resolved somehow the problem with window.onload = play_song; by myself.

18. Posted By: Ahmad - - December 31, 2008, 2:00 am
by following code, the player plays from the all list in frist page just one song and goes automatically to the next page
How is it possibile that the player plays all tracks in first page and then goes to next page?

// This is for Ie
if (song_status == 1) // song stopped
{ window.location = ''; // then load next page
} The player playing only one Track and goes to second page.

19. Posted By: Jeff - - December 31, 2008, 4:01 pm
Ahmad, to switch to a new page after all the songs have been played you would need to edit next_song(dir) function as follows.
The change is the lines that say:

if (current_song > playlist_length)
current_song = 0; // loop to first song

instead you would change it to:

if (current_song > playlist_length)
window.location = ''; // then load next page


20. Posted By: . - - January 1, 2009, 5:22 am

Thnaks, it works. Now wenn I change window.onload = loadsongs;
to window.onload = play_song; does`t play automaticaly songs wenn the page is loaded. I use IE 6.0 and Mozilla/5.0

21. Posted By: Jeff - - January 1, 2009, 12:33 pm
I never told you to change window.onload. Keep it as "window.onload = loadsongs;"

And as I said in a comment earlier:

Instead of waiting for a play button to be pressed, you could call the play_song() function from the very bottom of the function loadsongs()


22. Posted By: pawan vidya - - January 13, 2009, 2:11 am
hi , i m tring to play my selected song putted those in textarea but not successed.
plz heklp me how i paly song with this script.

23. Posted By: tomguiss - - January 18, 2009, 2:11 pm

i want my webpage to load and start automatically a song, and juste have a button with "pause" and after clicking the text on the button would be "play"

How can i make it ?

24. Posted By: Jeff - - January 19, 2009, 1:00 pm
In sound.js at the very bottom of the loadsongs() function add the line:


That will automatically start playing the music when the page is loaded. Then in your HTML document you could just put the control for the pause button:

<!-- Start of player controls
You can remove any of the controls if you do not
want to have them. You can also remove information
window DIV's at the bottom such as songname or songtime -->
<DIV STYLE="border: 1px solid black; width: 340px;
padding: 5px;">
<BUTTON ONCLICK="pause_song();" ID="pause_btn">Pause</BUTTON>


25. Posted By: Dino67 - - March 9, 2009, 2:24 pm
Thanks for the code. It works great except in IE7. If the user refreshes my page in IE7 while the music is playing, an error is generated: "Unhandled win32 exception". This error may occur on the first refresh or on the second refresh of the page. It does not occur with other browsers. I've asked friends to check and they are experiencing the same porblem so it's not unique to my system. Any ideas as to why that would be hapeening?

26. Posted By: Dino67 - - March 9, 2009, 2:27 pm
I forgot to add to my previous post that I have my music set to play when the page loads, using play_song(), and I only have a 'stop' button, no other control visible. Other than that, I have made no changes to the code.

27. Posted By: James Crossett - - May 20, 2009, 3:00 am
Getting this thing cross browser for me seems more to do with platforms. Windows and Mac. Detecting platforms and delivering either Windows media or Quicktime worked for me without any problem on any browser I tested in as you then deal with the native players.

So...add this function or replace detect_browser():
function detect_platform(){
var platform = navigator.platform;
return platform;

Load function becomes (just a change in the IF statement to merely detect Windows or assume Mac or something else)

function load(media){
media = folder + media;
var player = document.getElementById('player');

if (detect_platform() == "Win32"){
player.innerHTML = '

28. Posted By: ypki - - July 29, 2009, 2:00 am
Excellent work......
i have a doubt,
What happen when the music player is created and play a music file from server, will the music file is downloaded to the client system or it play from server?
If it download to the client system, where it save?
If it play from server, will it take more time to load?

29. Posted By: dbrumm - - September 18, 2009, 12:53 pm
Also had a problem with the refresh in IE7 and 8. It happens because the Display Time function is calling once the page is removed. I tried a few null statements like

if (typeof (document.getElementById("sound")) !== 'undefined' && document.getElementById("sound") != null) {

But still does not work. If you find a solution please let me know. Love the setup just have to solve this problem before I can use it.


30. Posted By: Reju Koshy - - September 27, 2009, 11:30 am
To avoid some java script errors in IE add following condition in display_time() finction...

song_status = document.sound.playState;

buffer_status =;

time = document.sound.controls.currentPositionString;
//duration = document.sound.currentMedia.duration;
duration = document.sound.currentMedia.durationString;