Search code examples
javascriptweb-audio-api

Volume changing when playing overlapping wav files with Web Audio API


In Google Chrome:

One .wav file is played, looping. Another .wav file is played from time to time as a sound effect.

When the sound effect plays, the volume of the looping sound automatically decreases. The volume gradually increases again over about 15 seconds.

(I guess it's automatically ducking http://en.wikipedia.org/wiki/Ducking )

I don't want the volume of the loop to decrease when the sound effect plays. How can I prevent this behaviour?

Example: http://www.matthewgatland.com/games/takedown/play/web/audiofail.html

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

var play = function (buffer, loop) {
    var source = context.createBufferSource();
    source.buffer = buffer;
    if (loop) source.loop = true;
    source.connect(context.destination);
    source.start(0);
};

var load = function (url, callback) {
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.responseType = 'arraybuffer';
    request.onload = function() {
    context.decodeAudioData(request.response, function(buffer) {
          callback(buffer);
        }, null);
    };
    request.send();
};

var musicSound;
var thudSound;
load("res/snd/music0.wav", function (buffer) {
    musicSound = buffer;
});
load("res/snd/thud0.wav", function (buffer) {
    thudSound = buffer;
});

Once the sounds have loaded, call:

play(musicSound, true); //start the music looping

//each time you call this, the music becomes quiet for a few seconds
play(thudSound, false);

Solution

  • You might have to do some sound design before you put this into your website. I don't know what you are using for an editor but you might want to edit the sounds together so that their over all level is closer to the level of the original looping sound. That way their won't be as dramatic a difference in levels that is triggering the automatic gain reduction. The combination of both sounds is too loud so the louder of the two will bring down the level of the softer one. So if you bring them closer together in level the overall difference shouldn't be as drastic when or if the gain reduction kicks in.