I'm encountering the problem that when the track playing in the list ends, I don't know how I can make it reload the next (random) track in the player. In general, when the theme finishes playing, it always loops, I only manage to get it to reload using a document.location.reload(false); in this part:
cargarCancion(aleatorio());
reproductor.addEventListener("ended", function(){
//cargarCancion(aleatorio());
document.location.reload(false);
I appreciate any help or ideas. Thank you very much!!!
<script>
var reproductor = document.getElementById("audio");
function cargarCancion(numero){
// Carga la canción de forma dinámica
var source= document.createElement('source');
source.src=lista[numero][0];
source.type="audio/mpeg";
reproductor.appendChild(source);
reproductor.load();
reproductor.play();
var titulo = document.getElementById("titulo");
titulo.innerHTML = lista[numero][1];
}
function aleatorio() {
return Math.round(Math.random()*(lista.length-1));
}
// Inicio listado
var lista = [["http://www.sonidosmp3gratis.com/sounds/008576979_prev.mp3","TEST UNO"],
["http://www.sonidosmp3gratis.com/sounds/short-circuit.mp3","TEST DOS"],
["http://www.sonidosmp3gratis.com/sounds/whistle-campana-whatsapp.mp3","TEST TRES"],
["http://www.sonidosmp3gratis.com/sounds/mario-bros%20vida.mp3","TEST CUATRO"],
["http://www.sonidosmp3gratis.com/sounds/messenger-tono-mensaje-.mp3","TEST CINCO"]];
// Fin listado
var listado = document.getElementById("listado");
for (x=0;x<lista.length;x++) {
var item = document.createElement("li");
item.innerHTML = lista[x][1];
listado.appendChild(item);
}
cargarCancion(aleatorio());
reproductor.addEventListener("ended", function(){
cargarCancion(aleatorio());
});
</script>
<audio id="audio"></audio>
<h3 id="sonando">Está sonando</h3>
<h1><div id="titulo"></div></h1>
<h2>Listado de temas:</h2>
<ul id="listado"></ul>
Your problem is that you are creating an element
source
for each call tocargarCancion()
and it will always play the first one:you can do it like this:
javascript: