我在页面上有一个html5 <audio>
标签,但我怎么知道它的持续时间?
<audio controls="">
<source src="p4.2.mp3">
</audio>
您正在尝试使用哪种浏览器?在某些浏览器上,duration
无法正常工作,如您所述,返回NaN
。
您还要确保在尝试检索持续时间之前已加载音频文件吗?
只需使用audioElement.duration
var au = document.createElement('audio');
au.addEventListener('loadedmetadata',function(){
au.setAttribute('data-time',au.duration);
},false);
2018解决方案:
当尚未加载音频元数据时,您将获得undefined
或NaN
(不是数字)。因此有人建议使用onloadedmetadata
来确保首先获取音频文件的元数据。此外,大多数人没有提到的是你必须用[0]
来定位音频DOM元素的第一个索引,如下所示:
- 香草Javascript:
var audio = $("#audio-1")[0];
audio.onloadedmetadata = function() {
alert(audio.duration);
};
如果这不起作用尝试这个,但不是那么可靠并且依赖于用户连接:
setTimeout(function () {
var audio = $("#audio-1")[0];
console.log("audio", audio.duration);
}, 100);
- JQuery:
$(document).ready(function() {
var audio = $("#audio-1")[0];
$("#audio-1").on("loadedmetadata", function() {
alert(audio.duration);
});
});
在上面的评论中,有人提到解决方案是将事件句柄绑定到事件loadedmetadata。这就是我这样做的 -
audio.onloadedmetadata = function() {
alert(audio.duration);
};
我使用“canplaythrough”事件来获取曲目持续时间。我有一个案例,我有两个球员,我想在第一个球员完成前2秒停止第二个球员。
$('#' + _currentPlayerID).on("canplaythrough", function (e) {
var seconds = e.currentTarget.duration;
var trackmills = seconds * 1000;
var subTimeout = trackmills - 2000; //2 seconds before end
//console.log('seconds ' + seconds);
//console.log('trackmills ' + trackmills);
//console.log('subTimeout ' + subTimeout);
//Stop playing before the end of thet track
//clear this event in the Pause Event
_player2TimeoutEvent = setTimeout(function () { pausePlayer2(); }, subTimeout);
});
我正在努力在React组件中加载持续时间,所以在@ AlexioVay的解决方案之后,如果您使用React,这里是一个答案:
这假设您使用ref
作为音频组件类,您需要为播放/暂停处理程序定位audio
元素。
<audio />
元素:
<audio ref={audio => { this.audio = audio }} src={this.props.src} preload="auto" />
然后在你的componentDidMount()
:
componentDidMount() {
const audio = this.audio
audio.onloadedmetadata = () => {
console.log(audio.duration)
this.setState({
duration: this.formatTime(audio.duration.toFixed(0))
})
}
}
最后formatTime()
功能:
formatTime(seconds) {
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
const s = seconds % 60
return [h, m > 9 ? m : h ? '0' + m : m || '0', s > 9 ? s : '0' + s]
.filter(a => a)
.join(':')
}
这样,加载音频src数据后,h:mm:ss
格式的持续时间将立即显示。甜头。
要获得阅读的结束,必须使用'onended'事件'loop = false'。如果loop = true,则onended不起作用;)
要制作播放列表,您必须设置loop = false才能使用'onended'事件来播放下一首歌曲。
如果您的脚本正确完成,您可以在任何地方恢复持续时间。如果'duration'的值为NaN,则浏览器找不到该文件。如果值为'Infinity''INF',则它是流式传输,在这种情况下,与读取时间'currentime'相比增加1 mn。对于* I.E它是废话。当前时间可能大于持续时间,在这种情况下你会这样做:var duration =(this.currentime> this.duration)? this.currenttime:this.duration;
那是(O_°)
最好使用这样的事件......
ObjectAudio.onprogress =function(){
if(this.buffered.length){
var itimeend = (this.buffered.length>1)? this.buffered.end(this.buffered.length-1):this.buffered.end(0);
....
Your code here.......
}
}