Pergunta

I wrote a bit of JavaScript with jQuery that loads a sound file with the HTML 5 <audio> tag and on a mouse click starts playing a new instance of that sound file (so that it can be played multiple times in parallel/overlay).

HTML:

<audio id="audiotemplate" src="audio/myfile.ogg"></audio>

JavaScript:

mybutton.click(function() {
    $('#audiotemplate').clone()[0].play();
});

This works as intended, but creates a memory leak that causes FF to eat up the system RAM and Chromium to show its "Ah, Snap" page if you click the button too many times.

EDIT: For a quick test better use $(document).keypress instead of mybutton.click and keep a button pressed.

How to clean up the <audio> element after the sound file has finished playing?

NOTE: I do not insert the cloned element into the the page.

NOTE 2: The leak also happens if you click, wait until the sound ends, klick again ...

(I am happy with a solution, but also appreciate an explanation why the leak happens at all.)

Foi útil?

Solução

Does this work any better?

mybutton.click(function() {

    var cloned = $('#audiotemplate').clone()[0];

    cloned.play();

    cloned.onended = function() {
        $(cloned).remove();
    }

});

Here on JSFiddle.

I can only guess about the leak, and that is some memory is reserved for every instance you clone, and when it finishes it doesn't auto clean up because you may need to access it again. For example, your browser doesn't know you only want it played once, so it will keep it around, because you may want to call play() on it again.

Using jQuery's remove() should free up that memory.

Update

How many times are you cloning it? You are aware this is a browser, and probably not optimised to have hundreds of audio elements being ran simultaneously?

I just cloned it ~300 ~600 times in Firefox 3.6 and it ran fine. It did crash for me after a few hundred on Chrome 8 though.

Here it is cloning via setInterval(). Do not click it if you think it will crash your browser.

Update

@alex: No, not simultaneously. My problem is that Chromium leaks memory even if the the sound is shorter than the respawn interval (as in Note 2) - so not playing at the same time, but after each other.

Does this still crash your browsers?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top