JQuery - for循环中的loadedmetadata监听器

时间:2014-04-24 09:41:02

标签: jquery html5 loops audio listener

我试图创建一个循环来获取jQuery中从数组中获取的不同音轨的持续时间。看起来好像在循环中添加一个事件监听器会覆盖for的第二个语句,无限循环并导致浏览器崩溃。

以下是代码:

var trackSources = new Array();
trackSources[0] = "music/haken.mp3";
trackSources[1] = "music/Drive home.mp3";
trackSources[2] = "music/Luminol.mp3";

var audioPlaylist = document.createElement("audio");
audioPlaylist.preload = "metadata";

function getDurations() {

    var max = trackSources.length;

    for (var i=0; i < max ; )
    {
        audioPlaylist.src = trackSources[i];

        audioPlaylist.addEventListener('loadedmetadata', function() {
            trackDuration= audioPlaylist.duration;
            alert(trackDuration);
            i++;
        }, false);

    }

}

有什么方法可以解决这个问题吗?谢谢!

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var trackSources = new Array();
trackSources[0] = "music/haken.mp3";
trackSources[1] = "music/Drive home.mp3";
trackSources[2] = "music/Luminol.mp3";

var trackDuration = new Array();

var audioPlaylist = document.createElement("audio");
audioPlaylist.preload = "metadata";
var i = 0;

function getDurations() {
console.log('getDurations called');
var arraySize = trackSources.length;
if(i < arraySize){
    $(audioPlaylist)[0].src = trackSources[i];
    $(audioPlaylist).on('loadedmetadata',function(){
        trackDuration[i]= $(audioPlaylist)[0].duration;
        console.log('Track '+i+' - duration: '+trackDuration[i]+' seconds');
        i++;
        $(this).off('loadedmetadata');
        getDurations();
    });
}
}
getDurations();
</script>

旁注:你提到了jQuery,但你的问题代码是普通的JS。