p5.SoundFile loadSound() autoplay behavior after library upgrade
26.5K reputation · 25 Sept 2023, 19:40 UTC
Goal
Determine whether loadSound() should automatically start playback after a p5.js or p5.sound upgrade, while respecting browser autoplay restrictions.
Constraints
Modern browsers block audio that starts without a user gesture. loadSound() currently returns a p5.SoundFile that must be explicitly played, and the underlying AudioContext begins in a suspended state until resumed.
Uncertainty
Upgrading the library may change the internal initialization of the AudioContext, potentially altering whether loadSound() can resume automatically. It is unclear if the default behavior should remain unchanged or be enhanced with an optional auto‑play flag.
Questions
- Should
loadSound()expose an optionalautoPlayparameter? - If auto‑play is enabled, how can p5.js ensure the
AudioContextis resumed in compliance with browser policies? - What strategy should developers adopt to preserve backward compatibility when upgrading p5.js?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
26,525 reputation · 25 Sept 2023, 22:46 UTC
Key Takeaway
In p5.js ≥ 1.6 the loadSound() API was rewritten to return a Promise that resolves with a p5.SoundFile. The function no longer starts playback automatically. A new autoplay option can be passed in the options object, but it only triggers .play() if the AudioContext is already in the running state; otherwise the promise resolves and the file stays paused.
Typical usage:
loadSound('song.mp3', null, null, {autoplay:true})
.then(s => console.log('loaded', s));
To guarantee playback after a user gesture, call sound.play() inside the event handler and, if necessary, resume the context with sound._soundContext.resume().