Play and pause one HTML5 audio element at a time through jQuery

I have several HTML5 audio elements per page and I use jQuery to play and pause them. Play and pause functions work properly, but tracks can play at the same time.

How can I rewrite this code to play only one song at a time? That is .. if you play and you click on another, pause the previous one and play the last click.

Thanks!

HTML:

<div id="music_right"> <div class="thumbnail" id="paparazzi"> <a class="playback"> <img class="play" src="http://www.lucisz.com/imgs/play.png" /> </a> <audio> <source src="../audio/fernando_garibay_paparazzisnlmix.ogg" type="audio/ogg" /> <source src="../audio/fernando_garibay_paparazzisnlmix.mp3" type="audio/mpeg" /> Your browser does not support HTML5 audio. </audio> </div> <div class="thumbnail" id="danceinthedark"> <a class="playback"> <img class="play" src="http://www.lucisz.com/imgs/play.png" /> </a> <audio> <source src="../audio/fernando_garibay_danceinthedark.ogg" type="audio/ogg" /> <source src="../audio/fernando_garibay_danceinthedark.mp3" type="audio/mpeg" /> Your browser does not support HTML5 audio. </audio> </div> <div class="thumbnail" id="bornthisway"> <a class="playback"> <img class="play" src="http://www.lucisz.com/imgs/play.png" /> </a> <audio> <source src="../audio/fernando_garibay_bornthisway.ogg" type="audio/ogg" /> <source src="../audio/fernando_garibay_bornthisway.mp3" type="audio/mpeg" /> Your browser does not support HTML5 audio. </audio> </div> </div> 

JavaScript: (works, but plays / pauses separately)

 $(function() { $(".playback").click(function(e) { e.preventDefault(); var song = $(this).next('audio').get(0); if (song.paused) song.play(); else song.pause(); }); }); 

JavaScript: (my ugly concept)

 $(function() { $(".playback").click(function(e) { e.preventDefault(); var song = $(this).next('audio').get(0); if (song.paused) song.play(); song.not($(this).pause(); else song.pause(); }); }); 
+7
source share
2 answers
 var curPlaying; $(function() { $(".playback").click(function(e) { e.preventDefault(); var song = $(this).next('audio')[0]; if(curPlaying) { $("audio", "#"+curPlaying)[0].pause(); } if(song.paused) { song.play(); } else { song.pause(); } curPlaying = $(this).parent()[0].id; }); }); 

That should work.

EDIT:

 var curPlaying; $(function() { $(".playback").click(function(e) { e.preventDefault(); var song = $(this).next('audio')[0]; if(song.paused){ song.play(); if(curPlaying) $("audio", "#"+curPlaying)[0].pause(); } else { song.pause(); } curPlaying = $(this).parent()[0].id; }); }); 
+6
source

This little feature works for me. It stops all other sound elements that are played on the page and allows those who have been started to continue playing. Here is the violin.

  $("audio").on("play", function (me) { jQuery('audio').each(function (i,e) { if (e != me.currentTarget) { this.pause(); } }); }); 
+3
source

All Articles