JohnPix
JohnPix

Reputation: 1833

Play audio one by one

I have a list of audio files. How to make them play one by one? Right now If I click button play, they are playing all together.

const audioList = [ 'audio1', 'audio2', 'audio3', 'audio4', 'audio5' ]

let button = document.querySelector('#btnPlay').addEventListener('click', e=>{
    audioList.forEach(element => {
        let audio1 = new Audio(element);
        audio1.play();
    });

Upvotes: 0

Views: 466

Answers (1)

PatrykBuniX
PatrykBuniX

Reputation: 152

You can achive this by using the audio element's 'ended' event and change the audio's src after end of each song.

my html file:

<audio src=""></audio>
<button></button>

my js file:

const songs = [ 'audio1', 'audio2', 'audio3', 'audio4', 'audio5' ]
const audio = document.querySelector('audio');
const button = document.querySelector('button'); 

let songIndex = 0;
audio.src = songs[songIndex]

audio.addEventListener('ended', () => {
  songIndex++;
  if(songIndex >= songs.length) return;
  audio.src = songs[songIndex]
  audio.play()
})

document.addEventListener('click', () => audio.play())

Codepen demo : https://codepen.io/PatrykBuniX/pen/GRgGGyr I hope it helped you! :D

Upvotes: 1

Related Questions