Web Audio Api : How do I add a working convolver?

后端 未结 2 453
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-07 19:14

What I am trying to learn / do: How to set up a simple working convolver (reverb) into my code sandbox below using an impulse response. I thought it was similar

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-07 19:45

    This is a pretty open-ended question; what have you tried that hasn't worked, or is the piece you're missing what the "impulse response" is supposed to be? If the latter, search for "impulse response files" and you'll find tons of free files you can use. You can also generate noise on a logarithmic decay curve into a buffer, and you'll get a basic reverb effect. Basic method to create an impulseResponse buffer:

    function impulseResponse( duration, decay, reverse ) {
        var sampleRate = audioContext.sampleRate;
        var length = sampleRate * duration;
        var impulse = audioContext.createBuffer(2, length, sampleRate);
        var impulseL = impulse.getChannelData(0);
        var impulseR = impulse.getChannelData(1);
    
        if (!decay)
            decay = 2.0;
        for (var i = 0; i < length; i++){
          var n = reverse ? length - i : i;
          impulseL[i] = (Math.random() * 2 - 1) * Math.pow(1 - n / length, decay);
          impulseR[i] = (Math.random() * 2 - 1) * Math.pow(1 - n / length, decay);
        }
        return impulse;
    }
    

    Your code has both a BufferSourceNode and the convolver pointing to the same buffer, which is almost certainly wrong; you don't usually play back an impulse response file using a buffersource, and you don't usually use a normal sound file as an impulse response. (Look up convolution on Wikipedia if the role of an impulse response isn't clear.) You need to do something like:

    function setupWebAudio() {
        var audio = document.getElementById('music');
        var context = new AudioContext();
        var source = context.createMediaElementSource(audio);
        var convolver = context.createConvolver();
        var irRRequest = new XMLHttpRequest();
        irRRequest.open("GET", "hall.mp3", true);
        irRRequest.responseType = "arraybuffer";
        irRRequest.onload = function() {
            context.decodeAudioData( irRRequest.response, 
                function(buffer) { convolver.buffer = buffer; } );
        }
        irRRequest.send();
    // note the above is async; when the buffer is loaded, it will take effect, but in the meantime, the sound will be unaffected.
    
        source.connect( convolver );
        convolver.connect( context.destination );
    }
    

提交回复
热议问题