使用jQuery控制音量

时间:2019-12-16 10:47:42

标签: jquery html audio

您好,我正在尝试为声音创建新的音量条,但是它不起作用,我在this上进行了搜索,并尝试再次将其放到Togheter中,但此刻第一个代码丢失了,所以我没有知道如何做到这一点。我做了类似的事情,但是我的声音无法自动播放,因此我无法更改声音的音量。如果我编写控件会自动播放,则整个栏会显示我不想要的。

  <input type= "range" class = "slider" id = "slider" value = "0" maxlength ="100">
<audio id ="audio-player" src = "test.mp3"></audio>


 $( document ).ready(function() {
$("#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);
}
});
});

3 个答案:

答案 0 :(得分:3)

您不必为此而使用jquery,这是仅使用本机javascript的一种可能方法:

slider.oninput = () => {
  console.log("Volume set to", ~~(slider.value))
  
  document.getElementById("audio-player").volume = ~~(slider.value) * 0.01
}
<input type= "range" class = "slider" id = "slider" value = "0" maxlength ="100">
<audio controls id ="audio-player" src = "test.mp3"></audio>

答案 1 :(得分:0)

这是一个快速的

$('#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>​

答案 2 :(得分:0)

尝试以下代码:

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      <script>
         $(document).ready(function(){
          $('#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;
             }
         });
         });
      </script>
   </head>
   <body>
      <div id="audioSlider"></div>
      <audio id="audio1" autoplay>
         <source src="http://commondatastorage.googleapis.com/codeskulptor-demos/DDR_assets/Kangaroo_MusiQue_-_The_Neverwritten_Role_Playing_Game.mp3" type="audio/mpeg" />
         Your browser does not support the audio element.
      </audio>
   </body>
</html>