How to pause all sounds when the browser is inactive?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By wellstackedd

I use Godot 3.5.1 and HTML5 to export my game.
When I launch the game in the browser and change the tab, the game itself pauses, but the music continues to play. I don’t know how to make the music stop along with the game when the browser tab is inactive.

:bust_in_silhouette: Reply From: Gluon

There is a stream pause option which you can use the following


If true, the playback is paused. You can resume it by setting stream_paused to false.

Documentation is found here

How can I know if the player has switched tabs in the browser?

wellstackedd | 2023-02-26 10:12

I would expect there is a JavaScript.evalfunction you can use but failing that well when they switch the browser to another tab the _process(delta) function will be stopped automatically so you may be able to work something through with a script on the audioplayer which checks in this function is still running. Maybe a boolean being switched on each process frame?

Sorry I dont write html games and also do not use javascript so I am not certain about that but the godot docs are here

Exporting for the Web — Godot Engine (stable) documentation in English

so this may help.

Gluon | 2023-02-26 16:12

Thanks for your reply. I found such a solution, in my case it worked.
I added this code to the autoload script:

func _notification(what):
	print("Sounds on")
elif what == MainLoop.NOTIFICATION_WM_FOCUS_OUT:
	print("Sounds off")

wellstackedd | 2023-02-26 16:28

:bust_in_silhouette: Reply From: trisolaran

First create a Javascript callback:

var tabcheat_callback = JavaScript.create_callback(self, "_on_tab_cheat")
var focuscheat_callback = JavaScript.create_callback(self, "_on_focus_cheat")

In _ready connect to the JS-Interface (there is more than “visibilitychange” and “focusout”, but I dont think, that you need more):

JavaScript.get_interface("document").addEventListener("visibilitychange", tabcheat_callback) 
JavaScript.get_interface("document").addEventListener("focusout", focuscheat_callback) 

Then define your methods:

func _on_tab_cheat(event):
	# do whatever you want


func _on_focus_cheat(event):
	# do whatever you want

should work with 3.5.1 and most Browsers, but maybe there are changes, did it more than a year ago.