JavaScript Tutorial JavaScript Examples JQuery Tutorial CSS Tutorial HTML Tutorial About Us

Playing Music

You can create a JavaScript that allows the user to play a music or an audio file. In order to play an audio file in a browser, you need to use the <audio> tag. The audio object is new in HTML5. The <audio> element has a number of properties, one of them is controls. The controls property sets or returns whether an audio should have controls displayed like play, pause etc.  View here for more properties of the audio object. We also need to use the <source> tag to reference the source of an audio file,  the syntax is as follows:

<audio controls>
<source src="music.ogg" type="audio/ogg">
<source src="music.mp3" type="audio/mpeg">


The <source> tag has to be used together with the <audio> tag Next, you can create a Play button using the play() method to start playing the music or audio file. The syntax is

It is often used together with the pause() method. The following is a sample script that can play a music file.

<audio controls id="music">
<source src="mj.mp3" type="audio/mpeg">
Your browser does not support the audio element.

<p>Click the buttons to play or pause the music.</p>

<button onclick="play()" type="button">Play </button>
<button onclick="pause()" type="button">Pause</button>

var myMusic= document.getElementById("music");
function play() {;

function pause() {

*You can use your own audio file instead of mj.mp3 file in this example.

Click the buttons to play or pause the music.

Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy