Why does AudioStreamPlayer sometimes not work?

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

I have a simple script:

if Input.is_action_just_pressed("left_mouse_button"):
	$ShootSound.play()

The only problem is, the sound sometimes doesn’t play. Seems like it didn’t load and after spamming LMB, the sound is working but if you don’t use it for sometime, it doesn’t play anymore until you try to use it again a few times.

:bust_in_silhouette: Reply From: Ertain

The reason for this could be that the sound is already playing. If left click/“fire” button is pressed repeatedly, the sound will be played from the beginning each time. What may have to be checked is whether the sound is playing:

if Input.is_action_just_pressed("left_mouse_button"):
    if not $ShootSound.is_playing():
        $ShootSound.play()

It may also be a good idea to put in a small “cool down” for the weapon, e.g. 0.2 or 0.3 seconds.

Remember that to play a sound multiple times, you need multiple AudioStreamPlayer nodes. This can be done easily by using an autoload such as this one: https://github.com/Calinou/escape-space/blob/master/autoload/sound.gd

Calinou | 2021-08-20 01:15