如何为HTML5音频元素制作加载栏? [英] How do I make a loading bar for an HTML5 audio element?

查看:135
本文介绍了如何为HTML5音频元素制作加载栏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为HTML5音频元素制作加载栏(显示加载/缓冲的百分比)。

I'm trying to make a loading bar (showing percentage loaded/buffered) for an HTML5 audio element.

对于视频标记,可以使用以下:

For the video tag it's possible to calculate using the following:

video.buffered.end(0) / video.duration

但我无法使用音频标签。它只返回一个修正值。

But I can't get this to work with the audio tag. It just returns a fix value.

任何想法?

谢谢!

推荐答案

缓冲上调用 end 方法,而不检查是不可靠的。你有可能试图无所事事地调用这个方法。检查这个小提琴:

Calling end method on buffered without checking is unreliable. It's possible you're trying to call the method on nothing. Check this fiddle:

document.querySelector('span').innerHTML = document.querySelector('audio').buffered.length;

<audio src="http://myst729.qiniudn.com/within-temptation_pale.mp3" controls autoplay></audio>
<p>Buffered Length: <span></span></p>

看?在第一个开始时,缓冲长度为0 - 没有加载任何内容。在调用 start end 方法之前,您需要确保缓冲长度不为0.

See? At the very first beginning, buffered length is 0 - nothing has loaded. You need to be sure that buffered length is not 0 before calling start or end method.

每当你读缓冲时,它确实是固定的。因此,要获得视觉上的加载效果,您需要反复阅读它。

Everytime you read buffered, it is fixed indeed. So, to achive a visually "loading" effect, you need to read it again and again and again.

这里我尝试每50毫秒更新一次加载和播放的百分比:

Here I try to update the loaded and played percentage every 50 millisecond:

var audio = document.querySelector('audio');
var percentages = document.querySelectorAll('span');

function loop() {
  var buffered = audio.buffered;
  var loaded;
  var played;

  if (buffered.length) {
    loaded = 100 * buffered.end(0) / audio.duration;
    played = 100 * audio.currentTime / audio.duration;
    percentages[0].innerHTML = loaded.toFixed(2);
    percentages[1].innerHTML = played.toFixed(2);
  }

  setTimeout(loop, 50);
}

loop();

<audio src="http://myst729.qiniudn.com/within-temptation_pale.mp3" controls autoplay></audio>
<p>Loaded: <span></span>%</p>
<p>Played: <span></span>%</p>

注意:您所在的位置可能无法访问MP3文件。如果是这种情况,请尝试另一个对您有利的来源。否则你会听到一个非常好的女声,并且不断看到百分比的变化,最终会达到100%。

NOTE: The MP3 file may not be accessible in your place. If that's the case, just try another source at your favor. Otherwise you will hear a very nice female vocal, and see the percentage changes continously, eventually ends up 100%.

这篇关于如何为HTML5音频元素制作加载栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆