How to release memory using Web Audio API?
Asked Answered
N

0

4
var context = new window.AudioContext()
var request = cc.loader.getXMLHttpRequest();
request.open("GET", 'res/raw-assets/resources/audio/bgm.mp3', true);
request.responseType = "arraybuffer";
request.onload = function () {
    context["decodeAudioData"](request.response, function(buffer){
        //success
        cc.log('success')
        window.buffer = buffer
        playBgm()
    }, function(){
        //error
    });
};
request.onerror = function(){
    //error
};
request.send();
function playBgm(){
    var audio = context["createBufferSource"]();
    audio.buffer = buffer;
    var _volume = context['createGain']();
    _volume['gain'].value = 1;
    _volume['connect'](context['destination']);
    audio["connect"](_volume);
    audio.start(0)
}

in my code I load a mp3 file and decode it into AudioBuffer(window.buffer) then I play it successful

but it cost a lot memory about 100MB How to release them? I tried like this

audio.stop()
audio = null
window.buffer = null
//context.close()
//context = null

chrome memory view

in the chrome memory view

sometimes the memory release in about 10second

sometimes release in about 1min

sometimes seems never release

I want to know if my code is the right way to release audiobuffer?

Do I need to close AudioContext?

Neall answered 26/8, 2017 at 15:7 Comment(2)
In addition to audio.stop() try audio.disconnect() if the node is connected to another node, for example the context, then there will still be a pointer left to it I assume.Wort
The answer here solved it for me: https://mcmap.net/q/785995/-web-audio-api-memory-leaks-on-mobile-platformsProtohistory

© 2022 - 2024 — McMap. All rights reserved.