P
P
Pavel2021-08-08 19:56:08
JavaScript
Pavel, 2021-08-08 19:56:08

How can I play an entire list of .mp3 files with an Audio() object?

Good day, dear connoisseurs!

There is a JavaScript code that should play all files one by one, by clicking on the button and pause when clicked back.

var tagAudio = document.getElementsByTagName("audio"); // получаем все ссылки
var array = []

for (let a of tagAudio) {
    array.push(a.getAttribute('src')) // наполняем масив ссылками
}

var el = document.getElementById('player');
var playing = false; // текущее состояние плеера

var player = new Audio();


for (let i = 0; i < array.length; i++) {
    player.src = array[i]
    player.preload = "auto";

    player.addEventListener('ended', function(){ // слушаем окончание трека
        console.log("до", playing)
        playing = false;
        console.log("после", playing)
    });
    
}

el.addEventListener('click', function(){ // слушаем клик по кнопке

    player.preload = "auto";
    
    if(playing){
        player.pause();
    } else {
        player.play();
    }

    playing = !playing;
    console.log("playing = !playing;", playing)

});


<button id="player" type="button">
          Воспроизвести
    </button>


The script works fine if we specify the link's index manually. If you run it through a loop, then everything does not work as it should, and only the last .mp3 file is specifically played, it skips everything from steel links.

It would not be bad to implement the substitution of the word "Play" for "Stop"

I would be grateful for any help.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-08-08
@bingo347

https://developer.mozilla.org/ru/docs/Learn/JavaSc...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question