Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to control HTML5 <audio> volume

Okay, I want to control the volume of an HTML5 element using the jQuery Slider element. I have implemented the slide, but can't figure out how to make the value of the slider take the place of the "audio player.volume = ?".

Any help is much appreciated.

Source

like image 364
futureslay Avatar asked Mar 06 '12 18:03

futureslay


2 Answers

The volume property is like opacity, it goes between zero and one, one being 100%.

Your code is so close, you just need to divide value by 100 when setting the volume of the <audio> element:

$("#slider").slider({
    value  : 75,
    step   : 1,
    range  : 'min',
    min    : 0,
    max    : 100,
    change : function(){
        var value = $("#slider").slider("value");
        document.getElementById("audio-player").volume = (value / 100);
    }
});

Notice I also put the change event handler inside the initialization of the slider widget.

When I paste the above code along into the console while on your webpage, and the volume slider worked as expected.

Also, you can bind to the slide event and the volume will change as the user slides the slider widget, not just after they finish moving the handle:

$("#slider").slider({
    value : 75,
    step  : 1,
    range : 'min',
    min   : 0,
    max   : 100,
    slide : function(){
        var value = $("#slider").slider("value");
        document.getElementById("audio-player").volume = (value / 100);
    }
});
like image 145
Jasper Avatar answered Sep 22 '22 22:09

Jasper


Here's a quick jsFiddle example (note: the audio begins on page load).

jQuery:

$('#audioSlider').slider({
    orientation: "vertical",
    value: audio1.volume,
    min: 0,
    max: 1,
    range: 'min',
    animate: true,
    step: .1,
    slide: function(e, ui) {
        audio1.volume = ui.value;
    }
});​

HTML:

<div id="audioSlider"></div>

<audio id="audio1" autoplay>
    <source src="http://www.w3schools.com/html5/song.ogg" type="audio/ogg" />
    <source src="http://www.w3schools.com/html5/song.mp3" type="audio/mpeg" />
    Your browser does not support the audio element.
</audio>​
like image 20
j08691 Avatar answered Sep 18 '22 22:09

j08691