Phaser 3: Audio not playing automatically

Hello everyone. I’m implementing audio in my game today. I’m having an issue. I have created a constructor that handles music as well as the toggle switch to mute/unmute music. When loading the game, I have to click my mute toggle and then unmute to hear the music. Any thoughts?

The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page. https://goo.gl/7K7WLu

Because in my code I’m creating a new MusicToggle which takes the scene and a song as the parameter, that way I can really customize it based on my scene/level without re-writing 50 lines of code.

this.levelMusic = new MusicToggle(this, "menuMusic");

I know the problem is that this.levelMusic is not being used yet, how can I make sure that the game knows that as soon as I create a new MusicToggle I want to initialize it?

Browsers do not allow you to play audio until the user has clicked somewhere on the page. Phaser takes care of unlocking the audio context, so you only have to make sure that the user has clicked before playing audio. If the music toggle is the first thing you click, you’re muting the sound immediately when you get permission to play it.

A common workaround for this is an overlay that requires you to click on it before the game starts. Alternatively, this.sound.locked from a scene will tell you whether the audio context isn’t allowed to play sound yet. You can use it to initialize the state of your MusicToggle.

1 Like