显示音频的缓冲百分比

时间:2017-12-09 11:11:54

标签: javascript html html5-audio

为什么我无法使用Javascript显示音频的缓冲百分比?



var audio = document.getElementById("aone1");
var percentages = document.getElementById("aone1l");

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 id="aone1" controls="controls">
   <source src="http://jainvidhya.epizy.com/Audio/Part1/ऑडियो नंबर 1 नमस्कार महामंत्र.mp4">
</audio>
<p>Loaded: <span id="aone1l"></span>%</p>
<p>Played: <span id="aone1l"></span>%</p>
&#13;
&#13;
&#13;

为什么音频需要花费很多时间才能加载?

1 个答案:

答案 0 :(得分:4)

使用唯一的id或在此使用类,这将为您提供一个数组,然后设置innerHTML

&#13;
&#13;
var audio = document.getElementById("aone1");
var percentages = document.getElementsByClassName("aone1l")

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();
&#13;
<audio id="aone1" controls="controls">
   <source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3">
</audio>
<p>Loaded: <span class="aone1l"></span>%</p>
<p>Played: <span class="aone1l"></span>%</p>
&#13;
&#13;
&#13;