p5.Sound 1.5.0: Should the global AudioContext be closed when a sketch ends?
0 reputation · 28 Sept 2024, 06:39 UTC
0 reputation · 28 Sept 2024, 06:39 UTC
In p5.js 1.5.0 the p5.Sound library added a patch that calls stop() and disconnect() on all AudioBufferSourceNode objects before freeing them, which eliminates the memory leak that appeared in 1.4.0. However, the library still keeps the global AudioContext alive, even after a sketch stops or is removed.
When using instance mode, multiple sketches can be created on the same page. Each sketch shares the default AudioContext, so if a sketch is disposed without closing the context, the context continues to hold unused nodes, potentially leading to cumulative memory growth over time.
The p5.js documentation does not specify whether the AudioContext should be automatically closed when a sketch ends, nor does it provide guidance on when to manually call audioContext.close(). This leaves developers uncertain about the best practice for long‑running applications or pages that load many sketches.
Unresolved questions:
AudioContext when all sketches have been disposed?AudioContext across sketches?AudioContext lifecycle to avoid memory growth while maintaining audio performance?AudioContext when a sketch ends unless you are completely destroying the audio feature or navigating away from the page entirely. In p5.sound 1.5.0, the AudioContext is treated as a singleton to avoid the overhead of re-initializing hardware resources across multiple sketch instances.
p5.js is designed for rapid creative coding, where sketches might be stopped and restarted frequently. If a sketch calls audioContext.close() upon disposal, the context enters a closed state that cannot be reopened. Any subsequent attempts to play audio in a new sketch will fail until an entirely new context is manually re-instantiated, which p5.sound does not always handle gracefully once closed.
When using instance mode where multiple sketches share one context, the primary memory concern is not the context itself, but the nodes attached to it. While version 1.5.0 improved cleanup via stop() and disconnect() on AudioBufferSourceNode, cumulative growth can still occur if custom nodes or buffers are not cleared.
If you are building a long-running Single Page Application (SPA) that loads and removes sketches repeatedly, follow these steps to prevent leaks:
disconnect() in your sketch's cleanup function.null to allow the garbage collector to reclaim memory.p5.Audio.close() when the user leaves the audio-enabled section or toggles sound off in settings.To verify if your sketches are leaking nodes, you can monitor the context state in the browser console after a sketch is removed:
// Check if the context is still active console.log(p5.Audio.context.state); // Count active nodes (Chrome-specific helper) console.log(p5.Audio.context.destination.context);
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.