Skip to content
Advertisement

HTML5 progress bar on audio – how to change audio position on click?

I recreated a fiddle of a similar code I am working on. The problem is that I cannot change the audio position. For example, if the audio is playing ad second 5, and I want to skip a part of the track and go to the end, it doesn’t change.

In the fiddle, the progress bar changes, but the audio continues without changes. In my test environment, the progress bar changes on click and then it immediately goes back to the right position the audio is playing, and also here the audio continues without changes.

What can I do to change the progress of the audio on click?

Here is my code:

const audio = $('audio')[0];

const progressBar = document.getElementById('progressbar');
function updateProgressBar() {
  const percentage = Math.floor((100 / audio.duration) * audio.currentTime);
  progressBar.value = percentage;
  progressBar.innerHTML = percentage + '% played';
}

$("#progressbar").on("click", function(e) {
  var max = $(this).width(); //Get width element
  var pos = e.pageX - $(this).offset().left; //Position cursor
  var dual = Math.round(pos / max * 100); // Round %
  if (dual > 100) {
    var dual = 100;
  }
  $(this).val(dual);
  progressBar.value = dual
});
<audio src="https://file-examples.com/wp-content/uploads/2017/11/file_example_WAV_10MG.wav"> </audio>
<progress id="progressbar" class="progress_controls" max="100" value="0"></progress>

<div id="play">
PLAY
</div>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

Advertisement

Answer

You need to add a currentTime event listener to your click function, here, replace your click function with this:

$("#progressbar").on("click", function(e) {
var progbar = $('#progressbar');
var pos = e.pageX - progbar.offset().left; //Position cursor
var percent = pos / progbar.width(); //Get width element
audio.currentTime = percent * audio.duration;
progbar.value = percent / 100;
});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement