Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() ?

like image 330
Fulligan Avatar asked May 24 '26 12:05

Fulligan


2 Answers

            context.decodeAudioData(byteArray, function(buffer).bind(cNote){
                scale[this].buffer = buffer;
            }, 
like image 164
cwilso Avatar answered May 27 '26 00:05

cwilso


You could move decodeAudioData into your storeNote function and pass your note as an argument. Like this:

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

        for (var note in scale){
            storeNote(note)    
        }

        function storeNote(note){
            var cNote  = MIDI["Soundfont"]["acoustic_grand_piano"][scale[note].name];
            if(cNote){
                var byteArray = Base64Binary.decodeArrayBuffer(cNote);
                context.decodeAudioData(byteArray, function(buffer){
                    scale[note].buffer = buffer;
                }, 
                function(err) {         
                    console.log("err(decodeAudioData): "+err); });    
                }
            } 
        }
like image 44
Julien Grégoire Avatar answered May 27 '26 00:05

Julien Grégoire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!