Audio Object Duration Keeps Changing?
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
Solution 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}, ...]
.
functioncomputeLength(file) {
returnnewPromise((resolve) => {
var objectURL = URL.createObjectURL(file);
var mySound = newAudio([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);
});
});
Post a Comment for "Audio Object Duration Keeps Changing?"