Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Video Volume Slider in HTML5 and JavaScript

I'm trying to make a video player with a custom UI using the HTML5 <video> tag and some JavaScript. My volume slider won't work though.

The way I've tried to do it is to write a function which sets the volume over and over at 1ms intervals. Obviously if they haven't touched the slider since the last cycle the volume shouldn't change. 1ms isn't a very long time so I tried increasing it to 100ms to see if it would help. It didn't.

No matter what position I set the slider to the volume stays at the default value. Can this be done without using a custom library? If so, how?

HTML:

    <video id="video" autoplay>
     <source src="/720p.mp4" type="video/mp4">
    </video>
    <input id="vol-control" type="range" min="0" max="100" step="1"></input>

JavaScript:

var video = document.getElementById('video');
var volu3 = document.getElementById('vol-control');

window.setInterval(changevolume(), 1);

function changevolume() {

 var x = volu3.value;
 var y = x / 100;

 video.volume = y;

}
like image 261
iHaveNoIdeaWhatI'mTalkingAbout Avatar asked Aug 10 '15 18:08

iHaveNoIdeaWhatI'mTalkingAbout


2 Answers

It's actually best to handle both the "input" and "change" event so that the volume updates in real-time with the slider with all newer browsers ("change" is only supposed to happen when the user releases the mouse button, even though it apparently works in Chrome, and IE10 requires you to handle "change" instead of "input"). Here's a working example:

<video id="video" autoplay>
    <source src="/720p.mp4" type="video/mp4">
</video>
<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('video');
        console.log('Before: ' + player.volume);
        player.volume = val / 100;
        console.log('After: ' + player.volume);
    }
</script>

...here's a live demo: https://jsfiddle.net/2rx2f8dh/

like image 117
Colin Avatar answered Oct 11 '22 18:10

Colin


Instead of checking whether the volume control has changed every millisecond (highly inefficient), you should create an event listener that will fire only when your volume control changes. Here is an example:

var video = document.getElementById('video');
var volumeControl = document.getElementById('vol-control');

volumeControl.addEventListener('change',function(){
    video.volume = this.value / 100;
});

UPDATE (with oninput event listener)

var video = document.getElementById('video');
var volumeControl = document.getElementById('vol-control');

var setVolume = function(){
    video.volume = this.value / 100;
};

volumeControl.addEventListener('change',setVolume);
volumeControl.addEventListener('input',setVolume);
like image 26
dhouty Avatar answered Oct 11 '22 16:10

dhouty