简体   繁体   中英

How to load multiple audio files into web audio API context with a single async call?

I'd like to load multiple mp3/ogg files from the server into Web-audio-api with a single call. I know that the for / loop below doesn't work, how do I get this going?

    var AudioCtx = new (window.AudioContext || window.webkitAudioContext)();
    var AudioBufferArr = [];
    
    for (let fileNumber = 1; fileNumber <= 4; fileNumber++) fetch_audiodata_from_server(fileNumber);
        
    function fetch_audiodata_from_server(fileNumber) {
        fetch("inc/postrequest.php",{
            method: 'POST',
            body: 'fileNumber=' + encodeURIComponent(fileNumber),
            headers: {'Content-type': 'application/x-www-form-urlencoded'}
        })
        .then(response => response.arrayBuffer())
        .then(buffer => {
            AudioCtx.decodeAudioData(buffer, function(decodedData) {
                AudioBufferArr[fileNumber] = decodedData;
            })
        });
    }

Thanks and cheers, Rob

The best solution would be if you just asked the server once. But if you insist of doing several Api calls you can use Promise all.

Note this is not a working example just an idea how you can use Promise All

let promiseList = [];
for (let fileNumber = 1; fileNumber <= 4; fileNumber++) {
  promiseList.push(fetchDataFromServer(fileNumber));
}

Promise.all(promiseList).then((values) => {
  //   *magic to the returned values*
});

function fetchDataFromServer(fileNr) {
  return new Promise((resolve, reject) => {
    fetch( ...insert code here...)
      .then((response) => response.arrayBuffer())
      .then((buffer) => {
           *more code with the buffer*
           resolve(*the data you want to return*)
      });
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM