[Tech Share] Simple Code for Volume Control and Mute Function

1dd9fd6f2905c424bf590f64671c1439

Step 1:

Create two clickable button nodes and a sphere node to represent the volume.

Step 2:

Create a parent node, and have the two buttons emit a signal to this script when “clicked”.

Step 3:

Create an audio playback node, add your music asset to it, and assign it to the “BGM” bus. (Enable [Autoplay] and [Loop].)

Step 4: Write a script on the parent node.

(1) Declare a variable to retrieve the index of the BGM bus.

var BGM = AudioServer.get_bus_index(“BGM”)

(2) Set up a global variable “Music Volume” to control the volume level.

(3) Retrieve this volume variable every frame and set the volume level for each value. (Here, I have set 9 levels.)

func _process(_delta: float) → void:
var music_volume = AGMakerManager.get_project_database_variable(“Music Volume”)
if music_volume == 0 :
AudioServer.set_bus_volume_db(BGM,-80.0)
$“Music/Music Sphere”.position = Vector2(-100,-184)
if music_volume == 1 :
AudioServer.set_bus_volume_db(BGM,-50.0)
$“Music/Music Sphere”.position = Vector2(-80,-184)

Step 5:

In the script handling the emitted signal, increase or decrease the value of the [Music Volume] global variable to adjust the volume.

func _on_MusicBig_pressed() → void:
var music_volume = AGMakerManager.get_project_database_variable(“Music Volume”)
if music_volume < 8 :
music_volume += 1
AGMakerManager.update_project_database_variable(“Music Volume”,music_volume)

func _on_MusicSmall_pressed() → void:
var music_volume = AGMakerManager.get_project_database_variable(“Music Volume”)
if music_volume > 0 :
music_volume -= 1
AGMakerManager.update_project_database_variable(“Music Volume”,music_volume)

[Done!!!]

5 Likes

Very good sharing! I’ve added it to my personal collection!

1 Like

[Add Mute Functionality]

Step 1:

Create a mute button and emit a signal to the main node script using the “pressed” signal.

Step 2:

Set up a global [Music Toggle] to control whether the volume is on or off. (Default is on)

Step 3: Write the mute control script on the main node

(1) In the signal script for the mute button press, control the global toggle variable.

func _on_MusicOff_pressed() → void:
var music_toggle = AGMakerManager.get_project_database_switch(“Music Toggle”)
if music_toggle == true :
AGMakerManager.update_project_database_switch(“Music Toggle”,false)
else :
AGMakerManager.update_project_database_switch(“Music Toggle”,true)

(2) Use frame-by-frame detection to check the [Music Toggle] to control the mute state.

func _process(_delta: float) → void:

Music mute control

var music_toggle = AGMakerManager.get_project_database_switch(“Music Toggle”)
if music_toggle == true :

Unmute

AudioServer.set_bus_mute(BGM,false)
if music_toggle == false :

Mute

AudioServer.set_bus_mute(BGM,true)

[Done!!!]