How to play sound when rapid fire

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

I recently make a game. When the player fire a single shot, the sound effect play once of course.

However, when I let player fire rapidly, the sound always play the front part of firing sound repeatedly. How can I let the following fire sound effect overlap on the previous one?
Thank you for your reading! I am appreciate for your generous help.

:bust_in_silhouette: Reply From: jgodfrey

First, I assume the initial problem is that you’re calling play() on your AudioStreamPlayer each time the fire button is pressed. Each call to play will play the assigned sound from the start. So, if that’s called in quick succession, the sound will never be allowed to finish, as it’ll constantly be restarted by the next call to play.

To fix it, you have a couple of typical choices.

First, you could make a simple change to only call play if the previously playing sound has finished. While that won’t allow multiple sounds to play at the same time, it will allow the shot sound to complete before replaying, and should be an improvement over your current setup. That could be as simple as something like this:

if !$AudioStreamPlayer.playing:
    $AudioStreamPlayer.play()

So, just wrap your current play() call with an if to ensure that it’s not currently playing.

Second, if you want to actually play multiple shot sounds at the same time, you’ll need to create some sort of AudioManager script that manages multiple AudioStreamPlayers (either statically or dynamically) - with each one playing it’s own instance of the sound.

Here’s a discussion I had with someone else on this topic that might be helpful here…

https://forum.godotengine.org/89015/audio-manager-design

Thank you! That is a great solution to solve the problem:)

Konishi | 2023-06-22 06:57

:bust_in_silhouette: Reply From: stormreaver

In my game, I created a scene that contains an AudioStreamPlayer3D that plays the appropriate sound (for my gun, I named the file gunshot.tscn, and gave it the class name Gunshot). I have a separate class for each weapon type that does the same thing for that weapon’s sound effects.

In code, I instantiate a new Gunshot object which automatically plays the sound when added to the scene tree. When the sound file is completely played (the AudioStreamPlayer3D’s finished() signal is emitted), the Gunshot object queue_free()'s itself.

Using this system, I can rapid fire to my heart’s content, and the sounds are mixed automatically.

Interesting. Instantiating a dedicated AudioStreamPlayer3D with each individual shot, while simple, sounds quite heavy to me. But, hey - if it’s working for your use-case, that’s great!

jgodfrey | 2023-05-27 00:40

I thought the same thing when I first conceived of it, but it turned out to have no noticeable effect on my game’s performance.

stormreaver | 2023-05-27 00:55