brookmarker brookmarker - 3 months ago 15
HTML Question

How can i pause/play audio using jQuery

Here is my audio in an

object
tag:

<object id="music" data="music.mp3">
<param name="autoplay" value="true" />
<param name="loop" value="true" />
</object>


I want to be able to pause/play the audio with a couple
a
tags:

<div id="music-on-off">Music:
<a href="#" id="music-on">On</a> | <a href="#" id="music-off">Off</a>
</div>


Can you tell me the jQuery to do this?

Answer

Use <audio> element, .play(), .pause()

html

<audio src="music.mp3" autoplay loop></audio>
<div id="music-on-off">Music: 
    <a href="#" id="music-on">On</a> | <a href="#" id="music-off">Off</a>
</div>

javascript

 $(function() {
   var audio = $("audio")[0];
   var controls = {
     "music-on": "play",
     "music-off": "pause"
   };   
   function playPause(e) {
     e.preventDefault();
     audio[controls[this.id]]()
   }
   $("#music-on, #music-off").click(playPause);
 });

jsfiddle http://jsfiddle.net/j3eL1nL8/1/