Search code examples
javascriptcallbackweb-audio-api

Storing Buffers in decodeAudioData callback method


I wanna make a little Browser App, that's able to play different notes. Therefor I have the sounds as Base64 encoded js-Variables. Now I have to decode the Base64 first an then the mp3 format to make the sound available to the App. Furthermore I have a datastructure called 'scale' which stores a simple c-Major scale like this:

scale = {
 'c': {
  color: 'red',
  name: 'C1'
 },
 'd': {
  color: 'darkorange',
  name: 'D1'
 },...

With the help of goolge and some tutorials I then do this to do the encoding:

    window.AudioContext = window.AudioContext || window.webkitAudioContext;
    var context = new AudioContext();

    for (var note in scale){
        var cNote  = MIDI["Soundfont"]["acoustic_grand_piano"][scale[note].name];
        if(cNote){
            var byteArray = Base64Binary.decodeArrayBuffer(cNote);
            context.decodeAudioData(byteArray, storeNote, function(err) { console.log("err(decodeAudioData): "+err); });    
        }
    }

    function storeNote(buffer){
        scale[note].buffer = buffer;
    }

Obviously the call inside storeNote doenst work correctly, because note is always the same. I'd like to have something like storeNote(buffer, note). However I can just use a callback-Function in decodeAudioData with no additional parameters but 'buffer'. Now the question is: How can I hand over the current note as a variable to storeNote() ?


Solution

  •             context.decodeAudioData(byteArray, function(buffer).bind(cNote){
                    scale[this].buffer = buffer;
                },