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.

music.js

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

function toggleMusic() {  
  var music = document.getElementById('music');
  if (music.paused) {
    music.play();
    document.cookie = "stopMusic=false";
  }
  else {
    music.pause();
    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.

index.html

<html>
  <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript" src="music.js"></script>
  </head>
  <body>
    <audio id="music" controls loop autoplay>
      <source src="music.ogg" type="audio/ogg" />
      Your browser does not support the audio element.
    </audio> 
    <div><a href="javascript:toggleMusic();">toggle</a></div>
  </body>
</html>

 

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

Reference:

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:

WordPress.com Logo

You are commenting using your WordPress.com 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