使用jQuery的HTML5音频持续时间 [英] HTML5 audio duration using jQuery

查看:126
本文介绍了使用jQuery的HTML5音频持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery获取音频持续时间,但很难获得它。我正在使用的方法定义如下

I am trying to get the audio duration using jQuery but having hard time getting it. The method I am using is defined below

var audioElement = document.createElement('audio');            
        audioElement.setAttribute('src','song.mp3');            
           audioElement.play();
           var duration = audioElement.duration;
               $(".songtime").html(duration);

但它表示 nan 有人有想法如何解决这个问题?

But it says nan Does anybody have any idea how to solve this?

推荐答案

由于音频尚未加载,因此您需要等到元素加载元数据后,方式来做到这一点:

Since the audio isn't still loaded, you need to wait until your element has the metadata loaded, there is a simple way to do it:

audioElement.addEventListener("loadedmetadata", function(_event) {
    var duration = audioElement.duration;
    //TODO whatever
});

这篇关于使用jQuery的HTML5音频持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆