Changing the volume

Hey!

I made a little change, so I can change the background music or the sfx volume!

In the start_menu scene I made 2 horizontal sliders:
2024-05-08 19_00_47-Window

I change the sliders a litte bit:

  • Set the value to 50
  • Set the step to 10

Also made signals for the slider value change, this is the start menu script:

extends Control

func _on_start_button_pressed():
	get_tree().change_scene_to_file("res://scenes/level.tscn")

func _on_button_exit_button_pressed():
	get_tree().quit()

func _on_bg_slider_value_changed(value):
	AudioPlayer.change_volume("bg", value)

func _on_sfx_slider_value_changed(value):
	AudioPlayer.change_volume("sfx", value)
	AudioPlayer.play_sfx("jump")

Finally in the audio_player scene’s script I made a change volume function (also created an sfx_volume_db variable, and set the sfx’s volume in the play_sfx function), here is the whole script:

extends Node

var hurt = preload("res://assets/audio/hurt.wav")
var jump = preload("res://assets/audio/jump.wav")

var sfx_volume_db = -10

func _ready():
	$MusicPlayer.volume_db = -10

func play_sfx(sfx_name: String):
	var stream = get(sfx_name)
	
	if stream == null:
		print("Invalid sfx name")
		return

	var asp = AudioStreamPlayer.new()
	add_child(asp)

	asp.stream = stream
	asp.name = "SFX"
	asp.volume_db = sfx_volume_db
	asp.play()
	
	await asp.finished
	asp.queue_free()
	
func change_volume(type: String, value: int):
	if type == "bg":
		$MusicPlayer.volume_db = float(value - 80) / 3
	elif type == "sfx":
		sfx_volume_db = float(value - 80) / 3

So now, in the main menu you can easily change the volume :slightly_smiling_face:

1 Like

Privacy & Terms