开发者

seek bar handling with javascript on HTML5 audio tag

开发者 https://www.devze.com 2023-01-13 04:41 出处:网络
I\'ve my codes as below <header> <audio src=\"friends_and_family_03.mp3\" id=\"audio\" controls></audio>

I've my codes as below

<header>
    <audio src="friends_and_family_03.mp3" id="audio" controls></audio>
    <input type="range" step="any" id="seekbar"></input>
    <script>
        seekbar.value = 0;
        var audio = document.getElementById("audio");

        var seekbar = document.getElementById('seekbar');
        function setupSeekbar() {
          seekbar.min = audio.startTime;
          seekbar.max = audio.startTime + audio.duration;
        }
        audio.ondurationchange = setupSeekbar;

        function seekAudio() {
          audio.currentTime = seekbar.value;
        }

        function updateUI() {
          var lastBuffered = audio.buffered.end(audio.buffered.length-1);
          seekbar.min = audio.startTime;
          seekbar.max = lastBuffered;
          seekbar.value = audio.currentTime;
        }
        seekbar.onchange = seekAudio;
        audio.ontimeupdate = updateUI;

    </script>
    <p>
        <button type="button" onclick="audio.play();">Play</button>
        <button type="button" onclick="audio.pause();">Pause</button>
        <button type="butt开发者_JAVA百科on" onclick="audio.currentTime = 0;"><< Rewind</button>
    </p>

</header>

This is as explained in http://dev.opera.com/articles/view/everything-you-need-to-know-about-html5-video-and-audio/

My problems are 1) The seekbar max value is not set according to the audio duration. (The seekbar width is just around half the audio duration). 2) The seekbar doesnt show any progress as the audio plays on but if you drag the seekbar, the currenTime actually changes.

Can anyone help me modify my code so that it functions properly??


If you are caught up with the same problem, here's the solution. (I got it from another forum). Just add these two lines:

audio.addEventListener('durationchange', setupSeekbar);
audio.addEventListener('timeupdate', updateUI);

Or maybe I was just a little too stupid!! lol

0

精彩评论

暂无评论...
验证码 换一张
取 消