我想我在 JavaScript Audio API 上发现了一个错误。
我的代码运行得非常完美:
var audio=new Audio();
var lastPause;
var myPlayer=document.querySelector('#player>.button.hand');
var playerStatus=("textContent" in document)?"textContent":"innerText";
myPlayer.addEventListener
(
'click',
function()
{
if(audio.paused)
{
audio.src="Nadav Guedj - Golden Boy (Eurovision 2015 - Israel - Karaoke).mp3";
myPlayer.innerHTML="►";
if(lastPause)
{
alert(lastPause); //If I remove this line it's not working when lastPause is defined!
audio.currentTime=lastPause;
}
audio.play();
}
else
{
myPlayer.innerHTML="||";
lastPause=audio.currentTime;
audio.pause();
}
}
);
但是
如果我删除或注释警告行 alert(lastPause);
当 lastPause
被定义或 iow 时音频卡住......用户第二次按下播放 (暂停后)。
最佳答案
我假设这个问题与 this question 有关我的回答也适用于此,
重复设置 audio.src
是你的问题。您有两种解决方法:
- 删除
audio.src
行,其他一些冗余代码也可以一起删除。 它在您使用警报时起作用的原因是,当警报被触发时,接下来的几行直到您关闭它才会执行,在这宝贵的几秒/毫秒内,源已更改的音频元素已经足够的时间来加载新的元数据,然后才能设置当前时间。因此您可以修改代码以在元数据加载时触发音频设置:
... myPlayer.innerHTML="►"; audio.play(); audio.onloadedmetadata = function(){ if(lastPause){ audio.currentTime = lastPause; } };
关于Javascript::audio.currentTime 仅在警报后正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29921674/