+2 votes

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():
     get_tree().change_scene("res://Level.tscn")
     $AudioStreamPlayer.play()

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.

in Engine by (40 points)

3 Answers

+2 votes

call the $AudioStreamPlayer.play() 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.

by (449 points)

Thanks Mam that worked

+3 votes

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:

$AudioStreamPlayer.play()
yield($AudioStreamPlayer, "finished")
get_tree().change_scene("res://Level.tscn")
by (20 points)

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!

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.

+1 vote

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 SelectSFX.play() above the code to change the scene.
  6. Try it out, it should work.
by (90 points)

This is easily the best answer

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.