问题
I’m trying to get the duration in seconds of every object in a list but I’m having some trouble in my results. I think it’s because I’m not fully understanding asynchronous behavior.
I start my function with an array songs[]
of n
number of objects. By the end of my function, the goal is to have an array songLengths
where the first value is the duration of the first object in songs[]
, and so on.
I’m trying to model my function after this example: JavaScript closure inside loops – simple practical example. But I’m getting undefined values for each songLengths[]
index.
$("#file").change(function(e) {
var songs = e.currentTarget.files;
var length = songs.length;
var songLengths = [];
function createfunc(i) {
return function() {
console.log("my val = " + i);
};
}
for (var i = 0; i < length; i++) {
var seconds = 0;
var filename = songs[i].name;
var objectURL = URL.createObjectURL(songs[i]);
var mySound = new Audio([objectURL]);
mySound.addEventListener(
"canplaythrough",
function(index) {
seconds = index.currentTarget.duration;
},
false,
);
songLengths[i] = createfunc(i);
}
});
回答1:
Something like this should work without a mess of closures, and with added clean asynchronicity thanks to promises.
Basically we declare a helper function, computeLength
, which takes a HTML5 File
and does the magic you already did to compute its length. (Though I did add the URL.revokeObjectURL
call to avoid memory leaks.)
Instead of just returning the duration though, the promise resolves with an object containing the original file object and the duration calculated.
Then in the event handler we map over the files
selected to create computeLength
promises out of them, and use Promise.all to wait for all of them, then log the resulting array of [{file, duration}, {file, duration}, ...]
.
function computeLength(file) {
return new Promise((resolve) => {
var objectURL = URL.createObjectURL(file);
var mySound = new Audio([objectURL]);
mySound.addEventListener(
"canplaythrough",
() => {
URL.revokeObjectURL(objectURL);
resolve({
file,
duration: mySound.duration
});
},
false,
);
});
}
$("#file").change(function(e) {
var files = Array.from(e.currentTarget.files);
Promise.all(files.map(computeLength)).then((songs) => {
console.log(songs);
});
});
来源:https://stackoverflow.com/questions/51797147/audio-object-duration-keeps-changing