Using jQuery to control HTML5 <audio> volume

Ok, I want to control the volume of an HTML5 element using the jQuery Slider element. I implemented a slide, but I can’t understand how to make the value of the slider by replacing "audio player.volume =?".

Any help is greatly appreciated.

A source

+4
source share
3 answers

The volume property is similar to opacity, it goes from zero to one, and 100%.

Your code is so close, you just need to divide the value to 100 at the mounting volume of <audio> :

 $("#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); } }); 

Note. I also put the change event handler in the initialization of the slider widget.

When I paste the above code into the console while on your web page and the volume slider worked properly.

In addition, you can snap to the slide event, and the volume will change as the user slides the slider widget, and 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); } }); 
+15
source

Here's a quick jsFiddle example (note: the sound starts when the page loads).

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>​ 
+4
source

In jQuery, you can get a DOM object just by using

 $("audio")[0] 

An example would be:
HTML

  <div class="audio-clip"> <h4>Clip 1</h4> <input type="button" class="play-button">Play</button> <input type="range" min="0" max="1" step="0.1"/> <audio src="http://www.w3schools.com/html5/song.mp3"></audio> </div> <div class="audio-clip"> <h4>Clip 2</h4> <input type="button" class="play-button">Play</button> <input type="range" min="0" max="1" step="0.1"/> <audio src="http://www.w3schools.com/html5/song.mp3"></audio> </div> 

JQuery

 $(document).ready(function() { $(".play-button").click(function(){ $(this).parent("div").find("audio").trigger('play'); }); $(".audio-clip input[type='range']").on("input", function(){ $(this).parent("div").find("audio")[0].volume = this.value; }); }); 
0
source

Source: https://habr.com/ru/post/1400070/


All Articles