gpt4 book ai didi

javascript - 音频持续时间返回 NaN 需要一些修改才能运行播放器

转载 作者:太空宇宙 更新时间:2023-11-04 14:30:13 24 4
gpt4 key购买 nike

每当我运行脚本时,它都会为音频持续时间返回 NaN

脚本

var mytrack = document.getElementById('mytrack'); 
var duration1 = document.getElementById('fullDuration');
duration1.innerHTML = parseInt(mytrack.duration);

HTML

<audio id="mytrack" controls autoplay>
<source src="kalimba.mp3" type="audio/mp3" />
</audio>
<span id="fullDuration">0:00</span>

最佳答案

始终建议使用 loadedmetadata 的事件然后调用他们将永远有效。在这种情况下最好使用事件监听器。

var a = document.getElementById('mytrack');
a.addEventListener("loadedmetadata", function() {
var duration1 = document.getElementById('fullDuration');
duration1.innerHTML = parseInt(a.duration);
}, true);

这会等待媒体加载完毕,然后设置 <span> 的内容标签。为获得最佳效果,请将此代码放在文档末尾 </body> 之前标记或使用窗口的加载事件:

document.addEventListener('DOMContentLoaded', function () {
var a = document.getElementById('mytrack');
a.addEventListener("loadedmetadata", function() {
var duration1 = document.getElementById('fullDuration');
duration1.innerHTML = a.duration;
}, true);
}, false);

如评论中所述,还有另一种使用 preload 的方法属性:

This enumerated attribute is intended to provide a hint to the browser about what the author thinks will lead to the best user experience.

但是既然你已经有了autoplay属性,我猜 preload没有必要。

The autoplay attribute has precedence over preload. If autoplay is specified, the browser would obviously need to start downloading the audio for playback.

关于javascript - 音频持续时间返回 NaN 需要一些修改才能运行播放器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38129171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com