jPlayer

HTML5 Audio & Video for jQuery

a project by happyworm

audio : As a soundtrack to your page

The following code will cause a piece of audio to automatically play and repeat when someone visits your webpage.

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="/js/jquery.min.js"></script>
  <script type="text/javascript" src="/js/jquery.jplayer.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $("#jquery_jplayer_1").jPlayer({
        ready: function() {
          $(this).jPlayer("setMedia", {
            mp3: "http://www.jplayer.org/audio/mp3/Miaow-snip-Stirring-of-a-fool.mp3"
          }).jPlayer("play");
          var click = document.ontouchstart === undefined ? 'click' : 'touchstart';
          var kickoff = function () {
            $("#jquery_jplayer_1").jPlayer("play");
            document.documentElement.removeEventListener(click, kickoff, true);
          };
          document.documentElement.addEventListener(click, kickoff, true);
        },
        swfPath: "/js",
        loop: true
      });
    });
  </script>
</head>
<body>
  <div id="jquery_jplayer_1"></div>
</body>
</html>

Note that this part of the code is so that iOS will start the playback when they click on the page. Without this code, browsers that require a gesture to initiate playback would never play the media. It is added to the ready event handler so that the media is always ready to accept the 1st click. The play is ignored if it was not required, since it was already playing anyway.

var click = document.ontouchstart === undefined ? 'click' : 'touchstart';
var kickoff = function () {
  $("#jquery_jplayer_1").jPlayer("play");
  document.documentElement.removeEventListener(click, kickoff, true);
};
document.documentElement.addEventListener(click, kickoff, true);

The user will have no control over the playback and the media will play until they leave the page.

Notes:

Forcing visitors to listen to music may cause them to leave your site.

Credit for the iOS click code goes to Remy Sharp.

The <!DOCTYPE html> was included in the example HTML for clarity. Forgetting to include it on the first line of HTML code is a common error.