运行 再次调用 While 函数,仅当特定数据已加载时

Running a While function again, only if specific data has been loaded

只有在成功加载外部音频文件的长度后,我才尝试让 while 函数再次 运行。

目标是检索数组中列出的每个音频文件的长度。

现在它只检索最后一个音频文件的长度。

我假设这是因为获取音频文件的长度需要一段时间,而 While 函数已经跳转到下一个循环。

代码如下:

var myList = [
  'https://mixergy.com/wp-content/audio/Nick-Bolton-Animas-on-Mixergy0721.mp3',
  'https://episodes.castos.com/5e7027dcc7b720-84196812/MicroCOnf-on-Air-Refresh.Ep.6.mp3'
]

var timeNow = 100;
var listLength = 0;


// Get audio file
// Create a non-dom allocated Audio element
var au = document.createElement('audio');


var i = 0;

while(i < (myList.length-1)) {
  // Define the URL of the MP3 audio file
  au.src = myList[i];
    console.log(myList[i])
    console.log(i)
    listLength = Math.round(au.duration);

  // Once the metadata has been loaded, display the duration in the console
  au.addEventListener('loadedmetadata', function(){
  // Obtain the duration in seconds of the audio file
  listLength = Math.round(au.duration);

    console.log(listLength)

  },false);

  i++;

}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>


    <script src="https://code.jquery.com/jquery-3.6.0.slim.js" integrity="sha256-HwWONEZrpuoh951cQD1ov2HUK5zA5DwJ1DNUXaM6FsY=" crossorigin="anonymous"></script>
    <script src="script.js" charset="utf-8"></script>
  </body>
</html>

这是因为函数保持引用同一个变化的变量au,所以当执行loadmetadata方法时它使用最新的元素。 您应该使用一个函数,在这种情况下 au 变量将成为该函数的局部变量,类似于:

function checkLength(src) {
  var au = document.createElement('audio');
  au.src = src;
  listLength = Math.round(au.duration);

  // Once the metadata has been loaded, display the duration in the console
  au.addEventListener('loadedmetadata', function(){
    // Obtain the duration in seconds of the audio file
    listLength = Math.round(au.duration);

    console.log(listLength)

  },false);

}

var myList = [
  'https://mixergy.com/wp-content/audio/Nick-Bolton-Animas-on-Mixergy0721.mp3',
  'https://episodes.castos.com/5e7027dcc7b720-84196812/MicroCOnf-on-Air-Refresh.Ep.6.mp3'
]

var timeNow = 100;
var listLength = 0;


// Get audio file
// Create a non-dom allocated Audio element
var i = 0;

while(i < (myList.length-1)) {
  // Define the URL of the MP3 audio file
  checkLength(myList[i]);
  i++;
}