Html 如何获得 html5 音频的持续时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11203773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:16:35  来源:igfitidea点击:

How can I get the html5 audio's duration time

htmlaudioduration

提问by hh54188

I have a html5 <audio>tag in page, but how can I know its duration time?

<audio>在页面中有一个 html5标签,但我怎么知道它的持续时间?

<audio controls="">
    <source src="p4.2.mp3">
</audio>

回答by AlexioVay

2020 solution:

2020年解决方案:

You will get undefinedor NaN(not a number) when the audio metadata isn't loaded yet. Therefore some people suggested to use onloadedmetadatato make sure the metadata of the audio file is fetched first. Also, what most people didn't mention is that you have to target the first index of the audio DOM element with [0]like this:

当音频元数据尚未加载时,您将获得undefinedNaN(不是数字)。因此有人建议使用onloadedmetadata来确保首先获取音频文件的元数据。此外,大多数人没有提到的是,您必须[0]像这样定位音频 DOM 元素的第一个索引:

-- Vanilla Javascript:

-- 原生 JavaScript:

var audio = $("#audio-1")[0];
audio.onloadedmetadata = function() {
  alert(audio.duration);
};

If this won't work try this, however not so reliable and dependent on users connection:

如果这不起作用试试这个,但不是那么可靠并且依赖于用户连接:

setTimeout(function () {
    var audio = $("#audio-1")[0];
    console.log("audio", audio.duration);
}, 100);

-- JQuery:

-- jQuery:

$(document).ready(function() {
   var audio = $("#audio-1")[0];
   $("#audio-1").on("loadedmetadata", function() {
       alert(audio.duration);
   }); 
});

回答by Fábio Zangirolami

var au = document.createElement('audio');
au.addEventListener('loadedmetadata',function(){
    au.setAttribute('data-time',au.duration);
},false);

回答by ThisClark

In a comment above, it was mentioned that the solution is to bind an event handle to the event loadedmetadata. This is how I did that -

在上面的评论中,提到解决方案是将事件句柄绑定到事件加载元数据。我就是这样做的——

audio.onloadedmetadata = function() {
  alert(audio.duration);
};

回答by joshuaiz

I was struggling with loading the duration in a React component so following @AlexioVay's solution, here is an answer if you're using React:

我正在努力在 React 组件中加载持续时间,因此遵循@AlexioVay 的解决方案,如果您使用的是 React,这里是一个答案:

This assumes you are using a reffor your audio component class which you will need to target the audioelements for your play/pause handler(s).

这假设您正在ref为您的音频组件类使用 ,您需要将audio播放/暂停处理程序的元素作为目标。

<audio />element:

<audio />元素:

<audio ref={audio => { this.audio = audio }} src={this.props.src} preload="auto" />

Then in your componentDidMount():

然后在您的componentDidMount()

componentDidMount() {

    const audio = this.audio

    audio.onloadedmetadata = () => {
        console.log(audio.duration)
        this.setState({
           duration: this.formatTime(audio.duration.toFixed(0))
        })
    }
}

And finally the formatTime()function:

最后是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(':')
}

With this, the duration in h:mm:ssformat will display as soon as the audio src data is loaded. Sweetness.

这样,h:mm:ss只要加载了音频 src 数据,格式中的持续时间就会显示出来。甜味。

回答by Patrick

I used "canplaythrough" event to get the track duration. I have a case where I have two players, and I want to stop the second player 2 seconds before the first one is complete.

我使用“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);

});

回答by Dave Hogan

Simply use audioElement.duration

只需使用 audioElement.duration

回答by Cherif

To obtain the end of reading it is necessary that 'loop = false' with the event 'onended'. If loop = true, onended does not work;)

为了获得阅读的结束,'loop = false' 与事件 'onended' 是必要的。如果 loop = true,则 onended 不起作用;)

To make a playlist, you have to set loop = false to use the 'onended' event in order to play the next song.

要制作播放列表,您必须设置 loop = false 以使用 'onended' 事件以播放下一首歌曲。

for the duration if your script is done correctly you can recover the duration anywhere. If the value of 'duration' is NaN the file is not found by the browser. If the value is 'Infinity' 'INF' it is a streaming, in this case, adds 1 mn compared to the reading time 'currentime'. For * I.E it's crap. Currenttime may be greater than duration, in which case you do: var duration = (this.currentime> this.duration)? this.currenttime: this.duration;

在持续时间内,如果您的脚本正确完成,您可以在任何地方恢复持续时间。如果 'duration' 的值为 NaN,则浏览器找不到该文件。如果值为 'Infinity' 'INF' 它是一个流媒体,在这种情况下,与读取时间 'currentime' 相比增加 1 百万。对于* IE,它是废话。当前时间可能大于持续时间,在这种情况下你会这样做: var duration = (this.currentime> this.duration)?this.currenttime: this.duration;

That's (O_ °)

那是(O_°)

回答by Cherif

it's better to use the event like this ...

最好使用这样的事件......

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.......
    }
}