Custom progress bar for <audio> and <progress> HTML5 elements

假如想象 提交于 2020-04-27 17:24:44

问题


I am mind boggled at working out how to create a custom seekbar for an audio player using the tag and simple Javascript.

Current Code:

    <script>
  function play() {
   document.getElementById('player').play();
  }

  function pause() {
   document.getElementById('player').pause();
  }
</script>


<audio src="sample.mp3" id="player"></audio>  
<button onClick="javascript:play()" >Play</button>
<button onClick="javascript:pause()" >Pause</button>
<progress id="seekbar"></progress>

Would it be possible to link the progress bar so that when i play a song the progress is shown?


回答1:


Yes, it is possible using the timeupdate event of the audio tag. You receive this event every time the position of the playback is updated. Then, you can update your progress bar using the currentTime and duration properties of the audio element.

You can see a working example in this fiddle




回答2:


If you want smooth progress bar,try somethink like that

HTML:

<div class="hp_slide">
     <div class="hp_range"></div>
</div>

CSS:

.hp_slide{
    width:100%;
    background:white;
    height:25px;
}
.hp_range{
    width:0;
    background:black;
    height:25px;
}

JS:

var player = document.getElementById('player');    
player.addEventListener("timeupdate", function() {
    var currentTime = player.currentTime;
    var duration = player.duration;
    $('.hp_range').stop(true,true).animate({'width':(currentTime +.25)/duration*100+'%'},250,'linear');
});

Pretty rough,but works




回答3:


First of all, don't use the progress element, it's a shitty element (for now) and styling it is a huge pain in... well it's boring (look at a little project I made, look at it (and it's juste webkit/moz)).

Anyway, you should read the doc on MDN, it's very easy and with a lot of examples. What you are looking for is the currentTime attribute, here a little snippet :

var audio = document.querySelector('#player')
audio.currentTime = 60 // will go to the 60th second

So what you need is to use the cross-multiplication (div is the element you use as a progress bar) : Where I clicked on div | THE TIME I WANT TO KNOW
————————————————————————————————————————
Total length of div | The total time of my video/audio (audio.seekable.end())



来源:https://stackoverflow.com/questions/12314345/custom-progress-bar-for-audio-and-progress-html5-elements

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