[英]HTML5 audio on IOS: how can currentTime be less than initial value?
我必须播放更大音频的短片段。 我使用currentTime
设置起始时间点,并使用timeupdate
事件在需要时停止音频。
我注意到,在很少的早期timeupdate
事件中,有时currentTime
小于其初始值,尽管(显然)没有“倒带”动作。
这是代码示例:
var start = 1;
var end = 1.3;
var audio = document.getElementById('audio');
audio.addEventListener('timeupdate', function () {
console.log(audio.currentTime);
if (audio.currentTime < start || audio.currentTime > end) {
audio.pause();
}
});
audio.currentTime = start;
audio.play();
例如,控制台日志的输出可以是:
1
0.85
0.85
1
1.02
...
这是一个例子 。
使用iOS 11.4.1在iPad上测试。 此问题仅在非常短的时间范围内出现~0.3秒。
起初你有一个错误的问题,因为你希望你的脚本在iOS上运行。 因此,你在标题中的问题是无关紧要的。 我们在iOS上有很多错误,iOS开发人员不想纠正它们。 这是一个错误。 写信给iOS支持并询问“怎么可能?”。
第二,你的帖子中有两个问题,因为你的脚本不能像你想要的那样在iOS上运行。
我为你写了解决方案。 在音频元素加载元数据(第一个错误)之前,请确保您没有尝试调用音频。 然后你有第二个错误:而不是:
if(audio.currentTime < start || audio.currentTime > end) //your mistake
你必须写:
if(audio.currentTime >= end)
解决方案(也适用于iOS)
var start = 1,
end = 1.3,
audio = document.getElementById('audio'),
button = document.getElementById('button'),
log = document.getElementById('log');
audio.addEventListener('timeupdate', function()
{
writeLog(audio.currentTime);
//your mistake: if(audio.currentTime < start || audio.currentTime > end)
if(audio.currentTime >= end)
{
audio.pause();
}
});
function writeLog(value)
{
var div = document.createElement('div');
div.innerHTML = value;
log.insertBefore(div, log.firstChild);
}
audio.addEventListener('loadedmetadata', function()
{
audio.pause();
button.removeAttribute('disabled');
});
button.addEventListener('click', function()
{
log.insertBefore(log.lastChild.cloneNode(!0), log.firstChild);
audio.currentTime = start;
audio.play();
});
#log
{
width:100%;
height:18em;
overflow-y:auto;
font:3em 'Courier New';
background:#069;
color:#7e0
}
#log div:last-child{display:none}
<!--
For this link from your example (on jsfiddle.net) is only a download is possible, but not using as source:
http://techslides.com/demos/samples/sample.m4a
-->
<audio id="audio" preload="auto">
<source src="http://techslides.com/demos/samples/sample.mp3" type="audio/mpeg"/>
<source src="http://techslides.com/demos/samples/sample.ogg" type="audio/ogg"/>
<source src="http://techslides.com/demos/samples/sample.aac" type="audio/aac"/>
</audio>
<button id="button" disabled style="width:9em;height:3em;font-size:3em">Play</button>
<br><br>
<div id="log"><div><hr></div></div>
SO上的代码段不起作用,因为它位于沙盒中。
请参阅codepen.io上的此工作示例 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.