I'm creating a game that uses HTML5 audio. Certain sounds may play more than once simultaneously (polyphony), so instead of using the original <audio>
elements, I keep references to them in an object, and then play them like this:
playSound(id) {
this.sounds[id].cloneNode().play();
}
My question is will the cloned node be garbage collected automatically, or do I need to worry about it? At least in Chrome the sound will play through, so the node is not removed immediately after the function exits, but since the node is not inserted into the DOM and I have no reference to it, I can't check whether it's removed from memory once the sound has finished playing.
Since the release of HTML5, audios can be added to webpages using the “audio” tag. Previously, audios could be only played on web pages using web plugins like Flash.
Garbage collection (GC) is a memory recovery feature built into programming languages such as C# and Java. A GC-enabled programming language includes one or more garbage collectors (GC engines) that automatically free up memory space that has been allocated to objects no longer needed by the program.
The garbage collector provides the following benefits: Frees developers from having to manually release memory. Allocates objects on the managed heap efficiently. Reclaims objects that are no longer being used, clears their memory, and keeps the memory available for future allocations.
According to this source, Audio can be garbage collected, but it does seem to imply you may need to use the new Audio()
constructor in JavaScript to make use of this feature rather than a reference to the HTML element.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement/Audio#memory_usage_and_management
Memory usage and management
If all references to an audio element created using the Audio() constructor are deleted, the element itself won't be removed from memory by the JavaScript runtime's garbage collection mechanism if playback is currently underway. Instead, the audio will keep playing and the object will remain in memory until playback ends or is paused (such as by calling pause()). At that time, the object becomes subject to garbage collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With