The Autoplay Policy: Why Every Sound App Needs One Click
Short answer: The browser created your AudioContext in a suspended state, because nobody has clicked anything yet. Call resume() inside a click or tap handler.
const audioCtx = new AudioContext(); // may start out suspended
startButton.addEventListener('click', async () => {
if (audioCtx.state === 'suspended') await audioCtx.resume();
startSound();
});
The message
In Chrome's console it reads: "The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page." Your code runs without an error and nothing comes out of the speakers.
Why browsers do this
Pages used to start playing sound the moment they loaded, mostly adverts. Browsers put a stop to it. Chrome's autoplay documentation says that an AudioContext created before the page receives a user gesture is created in the suspended state, and that this has applied to Web Audio since Chrome 71. Safari and Firefox have their own versions of the rule.
What counts as a gesture
A click, a tap or a key press. A page load does not count. Neither does a timer. The point is that a person asked for it.
Two things that caught me
It worked for me and not for a new visitor. Chrome keeps track of how much you play media on each site and relaxes the rule for sites you use a lot. So your own project may play straight away on your own machine and stay silent for everyone else. Test in a private window.
On a phone, start the sound directly inside the tap. If you wait for something else first, the phone may no longer treat it as the user's tap. I hit this with a different feature and wrote it up in Why Your Phone Screen Goes Dark and the Sound Stops.
Why sound apps have a start button
This is the reason. The "Enable Sound" button on my own project is that one click. It is not there for style, and no trick gets round it.
Sources
- Autoplay policy in Chrome: the suspended state, the fix and the Chrome 71 date
Try it: Ocean needs exactly one click, and then it plays for as long as you leave it. It is free, with no account.
Open Ocean, free