javascripthtmlhtml5-audio

Error when adjusting the volume of an audio tag with a range slider


I get Uncaught DOMException: Index or size is negative or greater than the allowed amount when adjusting the volume of an tag with a range slider.

I tried using this code:

function ppayVolume(){
        var volSlider = document.getElementById("volume");
    var realplayerEL = document.getElementById("real-player");
    var volVAL = document.getElementById("volume").value    
    realplayerEL.volume = volVAL
    console.log(volVAL)

But it will not work and show an error.


Solution

  • The error you're encountering, Uncaught DOMException: Index or size is negative or greater than the allowed amount, typically occurs when you're trying to set the volume property of an HTML <audio> or <video> element to a value outside the valid range, which is between 0.0 and 1.0.

    You need to scale the value of your slider from 0-100 to 0.0-1.0 before setting it as the volume.

    function ppayVolume(){
        var volSlider = document.getElementById("volume");
        var realplayerEL = document.getElementById("real-player");
    
        // Get the slider value (assuming it's 0-100)
        var volVAL = volSlider.value;
    
        // Scale the value to 0.0 - 1.0
        var scaledVolume = volVAL / 100;
    
        // Set the volume, ensuring it's within the valid range
        realplayerEL.volume = Math.min(Math.max(scaledVolume, 0.0), 1.0);
    
        // Optional: Log the scaled value
        console.log(scaledVolume);
    }