0

I have the following function

function calculateMFCC (wavFile, clipID) {
  var audioData = loadAudioData(wavFile);
  clipId = clipID;
  passToWavReader(audioData);
}

The function loadAudioData(wavFile) should load a wav file using Ajax and return result as an arraybuffer. This is how it looks like:

function loadAudioData(wavFile) {
  var request = new XMLHttpRequest();
    request.open('GET', wavFile, false);
    //request.responseType = 'arraybuffer';
    request.onload = function() {
        var audioData = stringToArrayBuffer(request.response);
      //passToWavReader(audioData);
      return audioData;
    }
    request.send();
}

When I debug the script, I see that in loadAudioData(wavFile) function the variable audioData gets the value it should get, but then when it returns to the function calculateMFCC (wavFile, clipID) the value audioData is undefined, so when it calls passToWavReader(audioData) the script breaks. So, the audioData variable from calculateMFCC somehow didn't get the value from loadAudioData.

Ana Mandic
  • 151
  • 4
  • 1
    Hint: which function is your return statement inside? – nnnnnn Mar 06 '16 at 13:03
  • Use a promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – Aral Roca Mar 06 '16 at 13:06
  • The **A** in async. You're trying to use the value before the call has returned. You have to think differently when you're using asynchronous functions, whether or not they're wrapped in other functions that *look* synchronous. – Dave Newton Mar 06 '16 at 13:11
  • @nnnnnn Oh, thank you. I didn't think about that. – Ana Mandic Mar 06 '16 at 14:31

1 Answers1

0

The problem is that the XMLHttpRequest doesn't respond in an instant. You need to add a callback. Try:

function calculateMFCC (wavFile, clipID) {
  loadAudioData(wavFile, function(audioData) {
    clipId = clipID;
    passToWavReader(audioData);
  });
}

function loadAudioData(wavFile, callback) {
  var request = new XMLHttpRequest();
  request.open('GET', wavFile, false);
  //request.responseType = 'arraybuffer';
  request.onload = function() {
    var audioData = stringToArrayBuffer(request.response);
    //passToWavReader(audioData);
    callback(audioData);
  }
  request.send();
}
Andrew Mast
  • 311
  • 1
  • 17