简体   繁体   中英

Set Default Volume in script

I have a website that loops music on load, but it is too loud. I have a slider bar to change the music volume, but how would I default it to 25% of the slider?

WEBSITE

<audio id=music loop autoplay src="peep.mp3">
  <p>If you are reading this, it is because your browser does not support the audio element.</p>
</audio>
<input id="vol-control" type="range" min="0" max="100" step="1" oninput="SetVolume(this.value)" onchange="SetVolume(this.value)"></input>

<script>
    function SetVolume(val)
    {
        var player = document.getElementById('music');
        console.log('Before: ' + player.volume);
        player.volume = val / 100;
        console.log('After: ' + player.volume);
    }
</script>

Just create a script that set the volume:

var audio = document.getElementById("music");
audio.volume = 0.25;

If you are using the audio tags, just get the DOM Node in Javascript and manipulate the volume property

var audio = document.querySelector('audio');
// Getting
console.log(volume); // 1
// Setting
audio.volume = 0.5; // Reduce the Volume by Half

The number that you set should be in the range 0.0 to 1.0 , where 0.0 is the quietest and 1.0 is the loudest.

  • input is a Void element and as such does not needs a closing </input>
  • You're using max , min , well, use also value .
  • Avoid using inline JavaScript. Keep you logic away from your markup.
  • init your function like setVolume()
  • use camelCase setVolume instead of PascalCase SetVolume , since it's a normal function, not a Method, Class or constructor...

 const audio = document.getElementById('audio'), input = document.getElementById('volume'), setVolume = () => audio.volume = input.value / 100; input.addEventListener("input", setVolume); setVolume(); 
 <audio id=audio loop autoplay src="//upload.wikimedia.org/wikipedia/en/4/45/ACDC_-_Back_In_Black-sample.ogg">Audio is not supported on your browser. Update it.</audio> <input id=volume type=range min=0 max=100 value=25 step=1> 

I think you'd also like this example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM