Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Efficient Code with WebAudio API

I am developing an HTML5 game and using Web Audio API for sounds. I am having an issue in which sounds start slowing down as game progress and game also starts feeling jerks which i guess is due to java-script GC doing memory cleanup.There are two types of sound i am playing in the game: 1) Background sound which continuously loop 2) Jump sound, hit sound etc occurs due to some event in the game which occurs very frequently. For example: firing multiple bullets from gun. Not sure what i am doing wrong, please help. Please refer below code

function play(){
    this.startTime = this.actx.currentTime;
    this.soundNode = this.actx.createBufferSource();
    this.soundNode.buffer = this.buffer;
    this.soundNode.connect(this.volumeNode);

    //If there's no reverb, bypass the convolverNode
    if (this.reverb === false) {
        this.volumeNode.connect(this.panNode);
    }
    //If there is reverb, connect the `convolverNode` and apply
    //the impulse response
    else {
        this.volumeNode.connect(this.convolverNode);
        this.convolverNode.connect(this.panNode);
        this.convolverNode.buffer = this.reverbImpulse;
    }

    this.panNode.connect(this.actx.destination);
    this.soundNode.loop = this.loop;

    this.soundNode.playbackRate.value = this.playbackRate;
    this.soundNode.start(
        this.startTime,
        this.startOffset % this.buffer.duration
    );
    this.playing = true;
 }
like image 275
AKSHAY BAIRAGI Avatar asked Jun 27 '26 20:06

AKSHAY BAIRAGI


1 Answers

There's nothing in your code that stands out as specifically memory intensive, apart from the use of the convolver (which can be really expensive and cause bad performance on lower-end devices). I'd try this though:

  1. Try disabling your audio (don't run any of the audio code, don't just mute it). Do you still have the janks in the game visuals? If so, it's not your audio that's the culprit.

  2. Try running your audio but always run it without the convolver. If the jank disappears, the convolver is your culprit. The only thing I could think of there is to try setting the convolver buffer only once and not every call to play().

  3. Try running different profiles in Chrome Dev Tools (JS, Memory, Paints etc.) and try to figure out where the janks come from. https://developer.chrome.com/devtools/docs/cpu-profiling

Good luck!

like image 171
Oskar Eriksson Avatar answered Jun 30 '26 08:06

Oskar Eriksson



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!