Search code examples
htmlaudioplayback

Playing Audio in HTML


I want to play a mp3 audio file in HTML. I don't want to display the whole player with controls like Volume etc. I just need a play/pause button, Designed by me, not the core design of some player, like yahoo player, or google one.

For example the audio will be autoplay. When a button (probably an image) is clicked it will pause, and when that image is clicked again, the audio will play again.

There are quite few examples here : http://www.w3schools.com/html/html_sounds.asp

Can I control any of them to play/stop from JS code ?


Solution

  • You can use the html5 audio tag. You can specify your own controls for playback.

    <audio preload="auto" autobuffer> 
      <source src="elvis.mp3" />
      <source src="elvis.wav" /> <!-- fallback if no mp3 support in browser -->
    </audio>
    

    This is a jQuery solution.

    http://jsfiddle.net/QPW27/109/

    This is what your non-jQuery solution would look like.

    var foo = document.getElementById('player');
    foo.pause();  //just bind play/pause to some onclick events on your page
    foo.play();
    

    Different browsers support different audio formats. You can specify fallback audio versions though. This website has a nice chart of browser support as of July 2011.