Cool Javascript MP3 Song Playback in Web Page with Custom Controls

Subscribe to Internet Tips and Tools Feed
Quick Jump
How to Use
How it Works
Off Screen DIV
Detect Browser
Load a Song
Object Tag
Embed Tag
Quicktime Functions
Quicktime MP3 ID3 Tag
Media Player Functions
Media Player ID3 Tag
Links
Javascript Progress Bar
Javascript Find on Page
Royalty Free Music at No Charge
Home Page


: Off
Volume:

Time:
1X

Features

  • 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

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="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,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="http://www.microsoft.com/Windows/MediaPlayer/"'
+ '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="http://www.apple.com/qtactivex/qtplugin.cab">'
+ '<PARAM name="SRC" VALUE="'+media+'">'
+ '<PARAM name="AUTOPLAY" VALUE="true">'
+ '<PARAM name="CONTROLLER" VALUE="false">'
+ '<PARAM name="VOLUME" VALUE="100">'
+ '<PARAM name="ENABLEJAVASCRIPT" VALUE="true">'
+ '<PARAM name="TYPE" VALUE="audio/wav">'
+ '<embed classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"'
+ 'name="sound"'
+ 'id="sound"'
+ 'src="'+media+'"'
+ 'pluginspage="http://www.apple.com/quicktime/download/"'
+ '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="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" specifies where to download the activex control for windows media player for the browser if they do not have it.

CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab" 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="http://www.microsoft.com/Windows/MediaPlayer/" specifies where they can download Windows Media Player if they do not have it.

pluginspage="http://www.apple.com/quicktime/download/" 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

Quicktime

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

enablejavascript="true"

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);
return;
}

Windows Media Player

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

document.sound.controls.stop(); // Stop
document.sound.controls.play(); // 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)
document.sound.network.bufferingProgress; // 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:
http://msdn2.microsoft.com/en-us/library/bb249349.aspx

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

Back to www.seabreezecomputers.com
Subscribe to Internet Tips Feed

View Comments

User Comments

There are 4 comments.

Displaying first 25 comments.

1. Posted By: tvradio - radiofono1@gmail.com - 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:
http://www.filefactory.com/file/8f29de

( 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: http://users.otenet.gr/~tvradio/javaplayer3.js
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
Greece


2. Posted By: tvradio - radiofono1@gmail.com - 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.(http://www.esnips.com)

My player can be found at http://users.otenet.gr/~tvradio/javajampa2.html

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)
radiofono1@gmail.com
http://users.otenet.gr/~tvradio



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?
YES | NO"

[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