Playing Music using JavaScript

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone

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">

</audio>

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

myAudioObject.play()

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.
</audio>

<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>

<script>
var myMusic= document.getElementById("music");
function play() {
myMusic.play();
}

function pause() {
myMusic.pause();
}
</script>

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

View Play Music to see the output.

 

 

 

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone