音频对象的持续时间不断变化? [英] 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 behavior.
我从对象数为n
的数组songs[]
开始我的函数.在我的函数结束时,目标是要有一个数组songLengths
,其中第一个值是songs[]
中第一个对象的持续时间,依此类推.
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.
我尝试在以下示例之后对函数进行建模:循环内的JavaScript闭合–简单的实际示例.但是我得到每个songLengths[]
索引的未定义值.
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);
}
});
推荐答案
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.)
但是,promise会使用包含原始文件对象和计算出的持续时间的对象来解析承诺,而不仅仅是返回持续时间.
Instead of just returning the duration though, the promise resolves with an object containing the original file object and the duration calculated.
然后在事件处理程序中,将我们映射到选择的files
上,以从中创建computeLength
承诺,并使用
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);
});
});
这篇关于音频对象的持续时间不断变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!