Reputation: 2212
Does anyone know a proper way to mute the sound in the game when tab or browser is inactive?
I've tried to do this by this(by JS libraries) way
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
visibilityChange = "mozvisibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
document.addEventListener(visibilityChange, handleVisibilityChange, false);
function handleVisibilityChange() {
$("video").prop('muted', document[hidden]);
}
but its not work for me. Thank you.
Upvotes: 2
Views: 3718
Reputation: 1
While using OnApplicationFocus will work it will also mute things if they switch to another window but you can still see the browser which may not be what you want.
If you go to the bottom of the thread below you'll see a post by someone from Unity and they give an example that uses the visibility change similar to what's in the original post but also has the Unity C# side that you'll need to actually get it to work. I didn't like hard coding the object name so I passed its gameObject.name when it calls the register function. I'm not used to working with jslib
plugins so initially, I didn't convert the pointer to a string in the jslib
using Pointer_stringify(str). If you do this you'll also want to set it to a local var or when an event triggers your string pointer could be anything.
Upvotes: 0
Reputation: 90630
Not sure but you probably could use OnApplicationFocus
and OnApplicationPause
on a controller component within Unity.
It could then enable and disable all sound by simply set AudioListener.pause
or alternatively the AudioListener.volume
accordingly
public class FocusSoundController : MonoBehaviour
{
void OnApplicationFocus(bool hasFocus)
{
Silence(!hasFocus);
}
void OnApplicationPause(bool isPaused)
{
Silence(isPaused);
}
private void Silence(bool silence)
{
AudioListener.pause = silence;
// Or / And
AudioListener.volume = silence ? 0 : 1;
}
}
Upvotes: 2