2

我正在尝试编写自己的 HTML5 音频播放器:您可以在这里查看

它在 IE9、FF、Chrome 中运行良好,但由于某种原因在 Safari 中运行良好,即使我已经听过

audio.addEventListener("loadedmetadata", tryThis, false);

它在播放前显示 NaN持续时间数据。

audio.setAttribute("src", a[trackNo][1]);
audio.load();
audio.addEventListener("loadedmetadata", tryThis, false);

function tryThis()
{
    this.addEventListener("timeupdate", function() { document.getElementById(radioPointer.toString()).innerHTML = formatTime(this.duration, this.currentTime);}, false);

    this.addEventListener("ended", function () { document.getElementById(radioPointer.toString()).innerHTML = formatTime(this.duration, 0); document.rootsPlaylist.roots[radioPointer].checked = false; }, false);

    this.play();    
}

<audio id="rootsPlayer" style="display:none;"></audio>

你能提供任何帮助吗?

非常感谢。

注意:您必须经常在歌曲之间切换才能明白我的意思,抱歉我忘了提及这一点。

4

1 回答 1

0

这样做的原因是duration属性仅在durationchange事件发出后才被初始化。因此,您可以使用isNan()函数或一些虚拟durationInitialized变量:

var durationInitialized = 0;
audio.setAttribute("src", a[trackNo][1]);
audio.load();
audio.addEventListener("loadedmetadata", tryThis, false);
audio.addEventListener("durationchange", function() {durationInitialized = 1;}, false);
function tryThis() {
 this.addEventListener("timeupdate", function() {
  var time = '';
  if (durationInitialized) time = formatTime(this.duration, this.currentTime);
  else time = formatTime(this.currentTime);
  document.getElementById(radioPointer.toString()).innerHTML = time;
 }, false);

 this.addEventListener("ended", function () {
  var time = '';
  if (durationInitialized) time = formatTime(this.duration, 0);
  else time = formatTime(0);
  document.getElementById(radioPointer.toString()).innerHTML = time;  
  document.rootsPlaylist.roots[radioPointer].checked = false; 
 }, false);

 this.play();    
}
于 2014-12-04T01:32:55.320 回答