[Tutorial - Web] Keep playing music when minimizing browser

Hello everyone!

I want to share the method I found to stop playing music in the game if the player switched to another tab or minimized the browser.

If I am not mistaken, then when switching the tab, the game completely freezes and the events are not executed. But the music is played asynchronously, that is, the sound engine works independently of the main game loop. Therefore, there is no way to check the state of the game and stop the music.

I found the solution in managing the game “externally” rather than from within the game. To do this, you need to edit the index.html file (which launches the game) and turn off or turn on music from it.
To do this, after publishing the game (Manually export your game as a HTML5 game on your computer [GDevelop wiki] ). You need to edit the index.html file, adding code to check the page display state and work with music.
We look at line 180 of the file:

//Initialization
var game = new gdjs.RuntimeGame(gdjs.projectData, {});

//Create a renderer
game.getRenderer().createStandardCanvas(document.body);

//Bind keyboards/mouse/touch events
game.getRenderer().bindStandardEvents(game.getInputManager(), window, document);
		
// ---------------------------
// Add the code - Check focus game (pause/play music)
// Adding a page visibility state handler
document.addEventListener ('visibilitychange', function () {
	// If the page is hidden
	if (document.visibilityState == 'hidden')
		// Pause music playing on channel 1
		game.getSoundManager().getMusicOnChannel(1).pause()
	else
		// In all other cases, we play music on 1 channel
		game.getSoundManager().getMusicOnChannel(1).play();
});
// ---------------------------

//Load all assets and start the game
game.loadAllAssets(function() {
    game.startGameLoop();
});

As described in the comments to the code, we monitor the state of the game page and stop or play music on a specific channel. For a description of this event handler for the html page, see the documentation (Document: visibilitychange event - Web APIs | MDN).

Hope you find this helpful! =)

3 Likes