Progress_bar for song

浪子不回头ぞ 提交于 2020-01-15 06:48:07

问题


i need a progress_bar that follow the time of a song. how can i set the end time of progress_bar exactly in the moment when the song finish?

ex. if my song has duration of 4:38 minutes how can i create a progress_bar for this specif period of time ( from when i click to 4:38 min after) ?

 var progressBar = $('#progress-bar'),
 width = 0;

 progressBar.width(width);

 var interval = setInterval(function() {
    width += 10;
    progressBar.css('width', width + '%');

    if (width >= 100) {
       clearInterval(interval);
    }
  }, 1000)

thanks.


回答1:


4:38 is 4 * 60 + 38 = 278 seconds, which means every second the bar should move (1/278)*100 percent

var step = 100/(minutes*60 + seconds);

var interval = setInterval(function() {
   width += step;
   progressBar.css('width', width + '%');

  if (width >= 100) {
     clearInterval(interval);
  }
}, 1000)



回答2:


Here is what I usually do:

var player = new Audio('http://goo.gl/mGVqyF');

player.play();
var winWidth = window.innerWidth;
var timer = setInterval(function(){
     document.getElementById('timebar').style.width = player.currentTime
                                                    / player.duration
                                                    * winWidth +'px';
},100);

// stop the setInterval when song ended
player.addEventListener('ended',function(){
    clearInterval(timer);
});

It does not guess when it is going to end, it grabs this info from the player with currentTime and duration.

JS Fiddle Demo




回答3:


Use related HTML5 media events like timeupdate and ended. You may see them in action at http://www.w3.org/2010/05/video/mediaevents.html

Regarding your code it would be like

var progressBar = $('#progress-bar'), width = 0;

progressBar.width(width);

$(audio).on('timeupdate',function(e){
  var progress = this.currentTime / this.duration;
  progressBar.css('width', progress*100+'%');
});

You probably don't use HTML5 media. So, anyway I don't recommend to use setInterval in that case. Use a ways similar to way I showed above.



来源:https://stackoverflow.com/questions/25650900/progress-bar-for-song

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!