There is a list of generated audio elements with a unique id:

<audio class="song" preload="auto" id="id-92" controls="controls"> <source src="../uploads/f2e49d34edc7fd037d2930f8d86552d5.mp3"> </audio> <audio class="song" preload="auto" id="id-93" controls="controls"> <source src="../uploads/f2e49d34edc7fd037d2930f8d86552d5.mp3"> </audio> 

I found the following code on stackoverflow.com javascript:

 $(function(){ $('audio').on('play', function() { $('audio').not(this).each(function(index, audio) { audio.pause(); }); }); 

It allows you to stop the currently played audio item if another audio item starts playing. Tell me how it can be improved, so that at the end of the playback of one, the next one will play?

  • This question has already been lit so many times (not only on this site), but what prevents you from using only one audio element on a page, and to switch to another track, only change its src ? With one element pad is simply impossible. - Oleg
  • @ Oleg, experience, it's all about him. even sometimes you need experience to find the right information. - Maxim Lyubitelev

1 answer 1

 let songs=[]; document.querySelectorAll('audio').forEach(audio =>{ songs.push(audio.id); audio.addEventListener('play', function(e){ document.querySelectorAll('audio').forEach(elem =>{ if (elem.id != e.target.id){ elem.pause(); } }) }) audio.addEventListener('ended', function(e){ let next = songs.indexOf(e.target.id) + 1; songs[next] === undefined ? next = 0 : songs[next] let nextSongs = document.getElementById(songs[next]); nextSongs.play(); }) }) 
 <audio class="song" preload="auto" id="id-92" controls="controls"> <source src="https://html5book.ru/examples/media/track.mp3"> </audio> <audio class="song active" preload="auto" id="id-93" controls="controls"> <source src="https://html5book.ru/examples/media/track.mp3"> </audio> <audio class="song" preload="auto" id="id-94" controls="controls"> <source src="https://html5book.ru/examples/media/track.mp3"> </audio>