Reputation: 2743
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>
Upvotes: 0
Views: 4080
Reputation: 106
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;
});
Upvotes: 2
Reputation: 551
You're missing two things - a listener to update the progress bar with the progress of the audio track, and a function to update the audio track currentTime according to your click on the progress bar. There are plenty of posts on SO already about this, please search first!
Audio Progress Bar html5 with interaction
Custom progress bar for <audio> and <progress> HTML5 elements
Upvotes: 2