Estoy tratando de hacer que una función while se ejecute nuevamente solo después de que haya cargado con éxito la duración de un archivo de audio externo.
El objetivo es recuperar la duración de cada archivo de audio que se ha enumerado en una matriz.
En este momento solo recupera la duración del último archivo de audio.
Supongo que esto se debe a que lleva un tiempo obtener la duración de un archivo de audio, mientras que la función Mientras ya ha saltado al siguiente bucle.
Aquí está el código:
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>Esto se debe a que la función mantiene la referencia a la misma variable au que cambia, por lo que cuando se ejecuta el método loadmetadata, utiliza el elemento más reciente. Debe usar una función y, en este caso, la variable au se volverá local para esa función, algo similar a esto:
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++; }