首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数,只有在加载了特定数据时,才能再次运行While函数。

函数,只有在加载了特定数据时,才能再次运行While函数。
EN

Stack Overflow用户
提问于 2021-09-14 08:27:05
回答 1查看 47关注 0票数 0

只有在成功加载了外部音频文件的长度之后,我才试图获得一个while函数来再次运行。

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

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

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

下面是代码:

代码语言:javascript
复制
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++;

}
代码语言:javascript
复制
<!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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-14 08:35:02

这是因为函数保持对更改的相同变量au的引用,所以在执行loadmetadata时,它使用最新的元素。您应该使用一个函数,在本例中,au变量将成为该函数的本地变量,类似于以下内容:

代码语言:javascript
复制
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++;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69174407

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档