In this section, I will show you how to add sounds when clicking buttons on the interface, etc.
Get the sound
To get the sound, I won’t need to give you the download link here, you just need to go to the Asset lib to find Kenney and it will come out.
You can choose one of the two.
Then click download to download it.
After downloading, click Install to install.
It will display an interface showing the address of that addon and then click Install
Then a new folder is created named addons and it contains the sound that I just installed in it
Regarding the audio files, it is also labeled with the name in front so you can know which one to use and which one to use.
Add to scene
After successful installation, I proceed to add it to the game.
Get yourself an AudioStreamPlayer2D node node
Here I am adding to the Menu scene.
Here I am doing Audio when I press the Start button so I will find the sound named click and drag it into the Stream of Audio Stream Player 2D.
After dragging is done, you can call it in code with the play() function.
extends Control func _on_NutBatDau_pressed(): $AudioStreamPlayer2D.play() yield(get_tree().create_timer(0,1),"timeout") get_tree().change_scene("res://Scences/Map/LevelMap.tscn") pass # Replace with function body. func _on_NutThoatGame_pressed(): get_tree().quit() pass # Replace with function body.
The line of code above, I added the line
$AudioStreamPlayer2D.play() I will play the sound when I press the start button
yield(get_tree().create_timer(0,1),"timeout"): is that I create a timer with a gin of 0.1s, after it runs out of 0.1s, it will run the change_scene() command. Here, I use this command because when I press just add the play() line and then change_scene it will not play the sound (depending on the device) so I will add the yield command so that after it plays the sound, then change scene.
You may not need to add yield() if the thing you want to play the audio doesn’t need to change the scene.
I will make one more in the PauseMenu scene.
You add sound.
Then in the function that shows the menu sound I have:
func _on_HienPauseMenu_pressed(): get_node("AudioStreamPlayer2D").play() $PauseMenu.show() get_tree().paused = true pass # Replace with function body.
Then after you press and test it, it will have a clicking sound when clicked.
So in this part, I showed you how to add sound to the game.