How to add sound to a button when it is clicked in the menu in Godot?

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

Can anyone tell how to add a sound to a button in a menu so when it is pressed it makes a sound?

Also remember that as the button is pressed, it should make a sound and should change the scene too.

 func _on_playagain_pressed():

I have done this code but when I click the button, it doesn’t make any sound even though I have set the sound on the Audiostreamplayer.

:bust_in_silhouette: Reply From: dustin

call the $ before you change the scene. if that still doesnt work, connect the $AudioStreamPlayer 's finished function to do the scene change so that it only changes the scene as soon as the audio has finished playing.

Thanks Mam that worked

Siddharth Pushkar | 2020-10-06 04:26

:bust_in_silhouette: Reply From: kamaem1517

You have to wait with the scene switching until the sound has finished to play, otherwise you won’t hear it. A quick way to do basically what dustin proposed is to yield until the finished signal is sent:

yield($AudioStreamPlayer, "finished")

Hi! Thanks I had same question.

Button sound is working when I click it, but now the scene does not change. Can someone help me? Thanks!

Guzzard8 | 2021-12-11 18:26

This works but if there is extra time in the sound it will wait until the empty part of the sound is over until it will change the scene. Another way to do it would be to use an autoload.

toivocat | 2022-08-24 19:48

:bust_in_silhouette: Reply From: toivocat

You can use autoloads to play the sound while switching between scenes,

  1. Create new scene.
  2. Add an AudioStreamPlayer as the root.
  3. Set the sound effects file as the “stream.”
  4. Make that scene an autoload with the name SelectSFX.
  5. In the on_Button_Pressed function write above the code to change the scene.
  6. Try it out, it should work.

This is easily the best answer

rocket 007 | 2022-11-12 10:15