HTML5 – Play sound/music with <audio> tag @ 2

Yesterday we talked about playing audio file in HTML5.
HTML5 – Play sound/music with <audio> tag @ 1

We can also take control of it using Javascript. Here is another example with a toggle link which can play and stop the music. jQuery is needed as well as the following Javascript file.


(function ($) {
	$(document).ready(function() {
    if (!getCookie('stopMusic') || getCookie('stopMusic') == "false") {
      var music = document.getElementById('music');;

function toggleMusic() {  
  var music = document.getElementById('music');
  if (music.paused) {;
    document.cookie = "stopMusic=false";
  else {
    document.cookie = "stopMusic=true";

function getCookie(cookieName) {
  var cookieVal = null;
  if (document.cookie) {
    var arr = document.cookie.split((escape(cookieName) + '=')); 
    if(arr.length >= 2) {
      var arr2 = arr[1].split(';');
      cookieVal  = unescape(arr2[0]);
  return cookieVal;


Add the jQuery and the above js file in the index.html. A toggle link is needed also.


    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src="music.js"></script>
    <audio id="music" controls loop autoplay>
      <source src="music.ogg" type="audio/ogg" />
      Your browser does not support the audio element.
    <div><a href="javascript:toggleMusic();">toggle</a></div>


By pressing the toggle link, we can play or pause the playing audio and the state is stored in cookie. Hope this article to help you getting start the HTML5 <audio> tag.

Done =)


One thought on “HTML5 – Play sound/music with <audio> tag @ 2”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s