Sound effect not playing

Godot Version

Godot4

Question

I’ve written a sfx_component, to play a sound effect. I’ve attached one it to my player component to play a sound effect every time I spawn a bullet, which works just fine. When I attach it to my destroy_component however, it doesn’t want to play the sound effect when an entity gets destroyed.

I’ve tried awiting the finished signal to let the code know that it cannot queue_free the base entity before the sound effect has finished playing, but I cannot seem to get it to work.

What am I doing wrong?

sfx_component.gd

class_name SfxComponent
extends Node

@export var sound_effect: Resource

var sfx_player: AudioStreamPlayer2D = AudioStreamPlayer2D.new()

signal sfx_done_playing

func _ready() -> void:
	add_child(sfx_player)
	sfx_player.stream = sound_effect

func play_sfx():
	sfx_player.play()
	sfx_player.finished.emit(func(): sfx_done_playing.emit())

func set_volume(volume: float):
	sfx_player.volume_db = volume

destroy_component.gd

class_name DestroyedComponent
extends Node

@export var entity: Node2D # The entity to destroy
@export var health_component: HealthComponent
@export var destroy_effect_spawner_component: SpawnerComponent
@export var sfx_component: SfxComponent

func _ready() -> void:
	health_component.death.connect(destroy)

func destroy() -> void:
	sfx_component.play_sfx()
	destroy_effect_spawner_component.spawn(entity.global_position)
	await sfx_component.sfx_done_playing
	entity.queue_free()

Can only one sound effect be playing at the same time? Since I am shooting all the time and playing that sound effect all the time?

You’re emitting your signal incorrectly here:

sfx_player.finished.emit(func(): sfx_done_playing.emit())

Should be:

await sfx_player.finished
sfx_done_playing.emit()

The rest looks correct.

I’ve applied your changes, but I still don’t hear the explosion sound effect being played

Try to include a couple of print() statements in your code to see if it is being triggered as you expect and let me know if you have any findings.

I did so, and the weird part is, it is being triggered in about 1/10 times. but even then, I only hear like a millisecond of the sound effect, and not the whole thing. I really don’t understand what the cause could be of it being so inconsistent.

Can you share your project through GitHub? I can try to debug it then.
Otherwise it’s hard to know your full scene structure.

@wchc Took a look, turns out the issue was that I was queue_free’ing in 2 locations, which prevented my sound to be played