I am needing to add a volume slider to my javascript player, and I have tried it this way:
//Slider control de volumen
let volume = document.getElementById('volume');
volume.addEventListener("change", function(e) {
source.volume = e.currentTarget.value / 100;
})
<input type="range" id="volume">
The problem that appears to me is that once the volume is adjusted, it works correctly, but when the fader is made between songs, the volume is no longer active as it has been adjusted, my question is, how can I get the volume to Once adjusted from the bar, is it constant once the songs change? Is it possible? I leave player code:
let play2 = false;
const fading= 10; // segundos de crossfading
function time_convert(num)
{
var hours = Math.floor(num / 60);
var minutes = num % 60;
return hours + ":" + minutes;
}
function cargarCancion(numero) {
// Carga la canción de forma dinámica
var source = new Audio(lista[numero][0]);
source.load();
source.play();
var titulo = document.getElementById("titulo");
titulo.innerHTML = lista[numero][1];
//mientras esta sonando...
source.addEventListener('timeupdate', (event) => {
let time1 = parseInt(source.currentTime)
let time2 = parseInt(source.duration)
document.getElementById("time").innerHTML =
time_convert(time1) + "/" + time_convert(time2);
//let volume = 1; //max
//Slider control de volumen
let volume = document.getElementById('volume');
volume.addEventListener("change", function(e) {
source.volume = e.currentTarget.value / 100;
})
// si estamos empezando y hay dos canciones sonando,
// el volumen empieza en cero y va subiendo
if (source.currentTime < fading && play2) {
volume = source.currentTime / fading;
console.log('Volumen subiendo');
} else if (source.currentTime > (source.duration - fading)) {
// ¿Ha empezado otra canción?
if (!play2) {
cargarCancion(aleatorio()); // Si no, carga la siguiente canción
play2 = true; //ya hay dos!
}
// estamos bajando el volumen...
volume = 1 - (source.duration - source.currentTime) / fading;
console.log('Volumen bajando');
}
source.volume = volume;
});
//canción terminada, no hay dos canciones a la vez sonando
source.addEventListener('ended', () => play2=false);
}
function aleatorio(){
return Math.round(Math.random() * (lista.length - 1));
}
var lista = [["https://storage.googleapis.com/media-session/sintel/snow-fight.mp3", "TEST UNO"],
["https://storage.googleapis.com/media-session/big-buck-bunny/prelude.mp3", "TEST DOS"]];
// Fin listado
let listado = document.getElementById("listado");
for (let x of lista){
let item = document.createElement("li");
item.innerHTML = x[1];
listado.appendChild(item);
}
<h3>
<div id="titulo"></div>
</h3>
<button id="play" onclick="cargarCancion(aleatorio());">Play</button>
<ul id="listado"></ul>
<div id="time"></div>
<input type="range" id="volume">
Thank you and I look forward to any help or suggestion.