p5.Sound 1.5.0: Should the global AudioContext be closed when a sketch ends?
28.1K 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:
- Should p5.js automatically close the global
AudioContextwhen all sketches have been disposed? - What are the performance implications of closing versus reusing the
AudioContextacross sketches? - How can developers best manage
AudioContextlifecycle to avoid memory growth while maintaining audio performance?