Jamen Jamen - 2 months ago 10
Javascript Question

How to Change the HTML5-audio Volume or Track Position with a Slider?

I know about the

.play()
, and the
.stop()
methods.

But is there a way to link up a slider to the volume? Or a slider to the track position? Is that possible?

And help is appreciated. Thanks!

Answer

jQuery UI makes it quite simple:

JS jQuery audio player with sliders

$(function() {

  var $aud = $("#audio"),
      $pp  = $('#playpause'),
      $vol = $('#volume'),
      $bar = $("#progressbar"),
      AUDIO= $aud[0];
  
  AUDIO.volume = 0.75;
  AUDIO.addEventListener("timeupdate", progress, false);
  
  function getTime(t) {
    var m=~~(t/60), s=~~(t % 60);
    return (m<10?"0"+m:m)+':'+(s<10?"0"+s:s);
  }
  
  function progress() {
    $bar.slider('value', ~~(100/AUDIO.duration*AUDIO.currentTime));
    $pp.text(getTime(AUDIO.currentTime));
  }

  $vol.slider( {
    value : AUDIO.volume*100,
    slide : function(ev, ui) {
      $vol.css({background:"hsla(180,"+ui.value+"%,50%,1)"});
      AUDIO.volume = ui.value/100; 
    } 
  });
   
  $bar.slider( {
    value : AUDIO.currentTime,
    slide : function(ev, ui) {
      AUDIO.currentTime = AUDIO.duration/100*ui.value;
    }
  });
  
  $pp.click(function() {
    return AUDIO[AUDIO.paused?'play':'pause']();
  });
  
});
#player{
  position:relative;
  margin:50px auto;
  width:300px;
  text-align:center;
  font-family:Helvetica, Arial;
}
#playpause{
  border:1px solid #eee;
  cursor:pointer;
  padding:12px 0;
  color:#888;
  font-size:12px;
  border-radius:3px;
}
#playpause:hover{
  border-color: #ccc;
}
#volume, #progressbar{
  border:none; 
  height:2px;
}
#volume{
  background:hsla(180,75%,50%,1);
}
#progressbar{
  background:#ccc;
}
.ui-slider-handle{
  border-radius:50%;
  top: -5px !important;
  width: 11px !important;
  height: 11px !important;
  margin-left:-5px !important;
}
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

<div id="player"> 

  <audio id="audio" src="http://upload.wikimedia.org/wikipedia/en/4/45/ACDC_-_Back_In_Black-sample.ogg" autoplay loop>
    <p>Your browser does not support the audio element </p>
  </audio>  

  <div id="volume"></div><br>
  <div id="progressbar"></div><br> 
  <div id="playpause"></div>

</div>

Comments