Friday, June 22, 2012

HTML5 and jQuery and the audio tag

I wanted to play a notification sound when something had completed, just for fun. I didn't want to show anything onscreen that said it was playing a sound, I just wanted it to play in the background.

This is how I did it:

<audio src="/includes/audio/fanfare.mp3" preload="auto" id="fanfare" autobuffer></audio>


<script type="text/javascript">
  $(document).ready(function() {
    $('#fanfare').trigger('play');
  })
</script>


Now, obviously, you can call that trigger('play') on any condition you like. I just wanted it to play as soon as it appeared as it was a through-Ajax part of the page. So, as soon as the process in question finished, it loaded, through $.ajax, the page containing the fanfare content above. Thus loaded, the fanfare played.