문제

I'm trying to create a loop to get the durations of different audio tracks taken from an array in jQuery. It appears like adding an event listener within the loop overrides the second statement of the for, looping indefinitely and causing the browser to crash.

Here is the code:

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);

    }

}

Is there any way to work it out? Thanks!

도움이 되었습니까?

해결책

You can try this:

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

On a side note: you mentioned jQuery but your question code is plain JS.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top