Hour 19. Sound
What You’ll Learn in This Hour:
Using player nodes to emit sound
Making use of positional audio with the Doppler effect
Adding effects to your sounds
Changing audio effects on certain game locations
In this hour, you will see the possibilities of using audio effects inGodot. You will learn how to add background music and sound effects, how to
use the automatic positional audio features, and how to add audio effects to post-process sounds in-game. You’ll also learn how to use
multiple buses and how to change the effects of audio based on the location of the emitting source.
Playing Sounds
Often overlooked, sound is a very important part of a game’s atmosphere, as it helps increase player immersion in the game world. There are
essentially two ways of playing audio inside Godot: directly to the output (as is common for background music) and from the position of the
player in the scene (usually for sound effects). This means you can have a stereo or surround setup without additional effort.
Importing audio files
Godot supports two audio formats out of the box: .wav and Ogg Vorbis. Ideally, you should use .wav files for short sound effects, since they are
faster to parse and play, and Ogg Vorbis for longer tracks such as music, because this format has compression and occupies less disk space.
In any case, Godot won’t force you to use a specific file, since music and effects are treated the same way by the engine.
NOTE
Streams vs. Samples
If you’re coming from Godot 2, you might notice the absence of distinction between streams and samples inGodot 3. In older versions,
streams were used for music and samples for effects. Godot 3 removes this distinction and can play both types from the same audio player
node.
There’s no special treatment to import audio files, so you’ll do it the same way as for other resources: simply copy them to your project folder.
They’ll appear in the file system dock as usual. Figure 19.1 shows the import options for both WAV and Ogg Vorbis files (see Figure 19.1).
FIGURE 19.1
Import options for WAVE and Ogg Vorbis files
AudioStreamPlayer
The simplest way to play an audio file is to use the
AudioStreamPlayer node. This node can be used both in 2D and 3D scenes, since it
inherits directly from
Node. It plays sounds straight to the output, disregarding the positional effects.
After adding this node to the scene, you’ll need to set up an audio stream to play. This property (see Table 19.1) can be loaded with any type of
audio file supported byGodot. Then you can enable the Playing property in Inspector to start playing the sound. It will loop, if set to do so;
otherwise, it will stop once the audio is finished.
TABLE 19.1 AudioStreamPlayer Properties
PropertyDescription
Stream
Sets the audio stream to be played. This can be any type of audio stream resource supported byGodot.
Volume
dB
Adjusts the gain of the audio in decibels. A value of 0 means no change in volume. A negative value means a reduction in sound,
while a positive value makes the sound louder.
Playing
Sets whether or not the sound is playing. You can check this in the Editor to hear the audio or set it via code to start or stop playing.
Autoplay Determines whether the sound will be played automatically when the scene starts.
Mix
Target
The final target of the audio. This can be set to Stereo, Surround, or Center. Stereo plays standard binaural sound, Surround uses
the player’s home theater system to play positional audio, and Center aurally focuses the audio in the center.
Bus
The audio bus is the sound output. Buses will be discussed in greater detail later in this hour.
TRY IT YOURSELF
Playing Audio
Let’s try to make something in the Editor play a sound. Assuming you already have an audio file in your project folder, you’ll just need to
111111111
22222222follow these steps:
1. Create a new scene in the Editor.
2. Add an
AudioStreamPlayer node (don’t select the 2D or 3D variant).
3. Drag the audio file from the file system dock to the Streamproperty in Inspector.
4. Click on the Audio tab in the bottom panel. The audio bus layout will show up.
5. Enable the Playing property in Inspector. The sound will start and the master bus meter will light up to show the audio levels.
6. Disable the Playing property and enable Autoplay instead.
7. Save and play the scene. There’s no meter in the running game, but you should be able to hear the sound playing.
TIP
AudioStreamRandomPitch
A type of stream that is not tied to any audio format is AudioStreamRandomPitch. This is a special type of resource that plays the audio with
a different pitch each time it starts. It can make sound effects such as hits and bullets sound a bit different every time, decreasing the audio
fatigue of the user.
You can create this effect in Inspector. It has two properties: the audio stream, where the actual sound comes from, and the random pitch
variation as a percentage. A value of 1 for the random pitch property will make the stream always sound the same, while larger values will
make it deviate from the original pitch.
Note that the pitch variation goes in both directions (the sound will sometimes have more bass, and at other times, more treble). The tempo of
the sound is also affected, since changing pitch while maintaining tempo is a time consuming process and can’t be done in real time.
Positional Audio
Godot offers a very simple way to enable positional audio in your games. Positional audio means the volume of the sound changes in each
speaker of a stereo or surround-sound setup so that the listener can associate the sound with a particular direction.
To enable positional audio, use the
AudioStreamPlayer2D node for 2D games and
AudioStreamPlayer3D for 3D games. They
can be put anywhere inside the game world, and the player will listen to the sound coming from that place, relative to where the current camera
is placed. The sound will be automatically sent to the correct speaker, based on where the player is inside the world and the direction he is
looking.
TIP
Audio Players as Children
Since positional audio usually comes from a specific game object, it’s interesting to put the stream player node as children of that object. The
sound will seem to come from it without any extra effort, since the player will follow the transform of its parent. This simplifies the creation of
realistic ambience sounds without worrying about the sound source position.
Positional Audio in 2D
In a 2D environment, positional audio is achieved with the
AudioStreamPlayer2D node (see Table 19.2). Since a 2D world has no
depth, this only affects left and right panning.
TABLE 19.2 AudioStreamPlayer2D Specific Properties
Property
Description
Max
Distance
The maximum distance the node can be heard in full volume. It will be attenuated when it’s farther than that value from the
camera.
Attenuation
Sets the attenuation curve. As with other curves, 1 is linear, smaller values are ease-out, and greater values are ease-in.
Area Mask
Sets which area layers can affect this player. Area effects will be presented in following sections.
If the node is in the center of the viewport, it will sound the same on both channels. It will play louder in the left channel and at a lower volume in
the right the farther the node goes to the left, and the opposite when it is going right. When the node goes too far, it will start losing volume until
it’s completely mute, so you don’t need to explicitly stop sounds that are too far away to be heard.
Positional Audio in 3D
When you have a 3D space available, the positional audio gets more interesting. With a depth dimension, you can create user surround audio
(if the user has the equipment to play it). For this, you’ll use the
AudioStreamPlayer3D node (see Table 19.3).
TABLE 19.3 AudioStreamPlayer3D Specific Properties
Property
Description
Attenuation
Model
Determines how the sound should attenuate when the source is farther away. It can follow an inverse, a square inverse, or a
logarithmic curve.
Unit dB
Increases the base sound volume in decibels.
Unit Size
Defines how much distance the sounds needs to attenuate. Larger values mean the node must be farther away to have a
111111111
22222222significant attenuation.
Max dB
Sets the limit of gain for the sound source. This prevents the audio from becoming too loud.
Max Distance
Sets how far the node must be from the source before it starts attenuating the sound.
Out of Range
Mode
Determines what to do when the sound source is too far away to be heard. You can pause the sound when it’s inactive, or
keep playing it with zero volume.
Area Mask
Like its 2D counterpart, this sets which area layers can affect this player.
Emission Angle If enabled, makes the source act like a speaker and emit the sound in a narrow direction. Listeners outside the range will hear
the sound as muffled.
Degrees
The wideness of the sound source, if the emission angle is enabled.
Filter
Attenuation dB
Determines how loud the sound is if the listener is outside the range of the emission angle. Lower values increase the amount
of muffle in the sound.
Cutoff
frequency
The frequency above which the sounds will be cut when the attenuation is being applied. This value applies both to the
emission angle and the distance attenuation.
dB (Attenuation
Filter)
Defines the amount of attenuation for frequencies below the cutoff point. Lower values will make the sound more muffled.
Doppler
Tracking
Enables or disables the Doppler effect for this source. “Idle” and “Fixed” refer to the processing frame, the same as the
_process() and _fixed() callbacks of a script.
Sounds that are far from the player start losing volume, independent of the direction those sounds travel. They also will use stereo or surround
panning, depending on the direction relative to the camera. It is possible to define an emission angle to the sound source to direct the sound
and muffle it for listeners outside the range (like a speaker does in real life) (see Figure 19.2).
FIGURE 19.2
The spatial audio player feature helps you place where the sound will come from.
NOTE
Audio Listener
Other game engines have the concept of an Audio Listener that represents the user “ear” inside the world, but this is not quite the case for
Godot. The sound listener is the current camera by default, so there’s no extra step to set up a listener.
In case you need a listener in the world that is not in the same position as the camera, you can override it by adding a
Listener node and
enabling its Current property.
Doppler Effect
The Doppler effect is the compression and expansion of sound waves when the sound source and listener are moving in relation to each other.
This makes the frequency of the sound go higher if the source is approaching the listener, and lower if it’s moving away. The practical effect is
the sound distortion that you hear from the siren of a fast ambulance and from the horn of a moving train or truck.
Enabling such an effect inGodot is very simple. First, enable Doppler tracking in the current
Camera node. Then do the same to the
AudioStreamPlayer3D node that acts as your sound source. The choice for “Idle” or “Fixed” should adjust to the needs of your game, so you
should try both and see what works best.
Once the Doppler effect is enabled, if the sound source or the camera is moving, you will hear the distortion in the sound.
Audio Buses
People with audio backgrounds will be familiar with the concept of buses. Essentially, a bus is a route for audio signals that can either go to
another bus or directly to the output. Each bus can have its own volume and chain of effects, giving you the flexibility to process audio any way
you want and reuse effects.
The Master bus is the main bus, and can’t be renamed or deleted. Every audio signal eventually goes to the Master bus, and from there, it
follows the user’s audio output.
TIP
Using the Master Bus
It might be tempting to change the volume or apply effects to the Master bus (see Figure 19.3). However, you should avoid it. This bus is the
final link in the chain for all game audio, so effects would be applied to everything. While this might be intended, it may also bite you if you want
to add another sound without those effects.
FIGURE 19.3
The Master bus as it is by default
Instead, create a new bus for global effects and route all other sounds there. This way, you can add sounds that bypass those global effects if
need be. This is useful even for typical master effects, such as a limiter.
111111111
22222222Bus Layout
Clicking the Audio button in the bottom panel will bring up the Bus Layout Editor. Here, you can add and remove buses, change and edit their
effects, and adjust their volumes.
It’s also possible to create, save, and load layouts. Note that a layout is enabled for the project and not for individual scenes. You can change
the bus layout during runtime by calling the set_bus_layout() function of the AudioServer singleton.
NOTE
Default Bus Layout
When you make changes to the bus layout, Godot automatically creates a file called default_bus_layout.tres and saves it on the root
of your project. As the name implies, this is a default bus layout for the entire project, and it can be easily recalled by clicking the Load Default
button on the Bus Layout Editor.
TRY IT YOURSELF
Changing Buses and Effects
In this exercise, you’ll use some of the functions of the bus layout Editor.
1. Click on the Audio button of the bottom panel to bring up the bus layout Editor, if it’s not open already.
2. Create a new bus by clicking the Add Bus button at the top of the panel (see Figure 19.4).
FIGURE 19.4
The bus layout after adding buses and effects
3. Rename the new bus “Effects.”
4. Click on the Add Effect button of this bus and select Distortion.
5. Select the Distortion effect by clicking on its name. You can see and change the effect properties in Inspector.
6. Create a new bus and call it “Reverb.”
7. Add a Reverb effect to this new bus.
8. On the bottom of the bus, there is a dropdown menu with M
a
ster selected. Change this dropdown to Effect instead. This is the
target output of the new bus.
Bus Chain
As indicated in the previous exercise, you can select the target output for every bus in the layout, so you can make a sound go into a series of
buses before finally reaching the output. This can be useful for adding effects to specific sounds by making them go into a targeted bus that
proceeds to send the audio to another effect bus.
However, there are a few rules to this layout. First, the buses have only one output. You cannot make copies of the sound to send to another
bus (this is usually called “sends” in professional audio software, but Godot does not have this function). The second rule is that you can only
send the output to buses to the left of the current one. This avoids signal loops.
You can move buses by clicking and dragging them to the desired positions. The output target will be changed automatically if you set the bus
into a position that puts it to the left of the previous target bus.
Solo, Mute, and Bypass
There is a set of three buttons in each bus that can solo, mute, and bypass the bus. Here’s a simple breakdown:
Solo: Mutes all other buses except the one playing. You can solo multiple buses, and all the ones that are soloed will be active.
Mute: Inactivates the bus by setting the volume to zero. Sounds sent to muted buses won’t be played.
Bypass: Ignores all the effects and makes the sound pass through the bus as if all the effects were disabled. Note that you can also
disable effects individually by clicking on the checkboxes beside them.
Area Effects
Besides the positional audio in terms of speaker sets, Godot has effects that can be applied to sound when the audio player is inside a certain
game area. This allows effects such as increased reverb when the player character is inside a cave, or a muffled sound when the character is
underwater.
2D Audio Area Effect
If you are making a 2D game, you can also avail yourself of the area effects. First you’ll need an area, which can be set up with the
Area2D node (the same node that interacts with the physics engine).
111111111
22222222The
Area2D node has a special property that can redirect its sounds to a specific audio bus. You can change the effects applied to the
AudioStreamPlayer2D sound by sending it to a different bus loaded with the desired effects.
Like in the physics engine, you’ll need to add a
CollisionShape2D node (or a
CollisionPolygon2D) as a child of the
Area2D
so it has an actual area of effect. When the audio player is inside the shape (based on its position property), its sound will be redirected to the
other bus.
3D Audio Area Effect
In 3D, the area effect is a bit more powerful, since you can have a Reverb Bus. It still has the same properties as the 2D counterpart, so it can
redirect the sounds played inside it to another bus. Note that you still must add a child
CollisionShape (or
CollisionPolygon) to
determine the affected area.
If enabled, the Reverb Bus property creates a copy of the sounds played inside the area and directs it to the specified bus. This is quite
common in professional audio mixing, because you can send multiple sounds to the same reverb bus while maintaining the characteristics
(and effects) of the individual audio sources. Table 19.4 shows the specific properties of the
Area node that are related to the Reverb
Bus.
TABLE 19.4 Area Reverb Bus Properties
Property Description
Enable
Enables the audio copy to the reverb bus.
Name
The name of the bus to which the audio copy will be sent.
Amount
The volume of the audio that will be sent to the reverb bus as a percentage of the original audio. This effectively affects the amount
of reverb (or any other applied effect) that the user will hear.
UniformityThe uniformity of the effect inside the area, such as how the position of the object will affect the panning of the reverb bus. A value of
0 means the audio signal to the bus will be completely dependent of the position of the source. A value of 1 means complete
independence, so the original audio will be sent to the reverb bus.
Dynamic Audio
While Godot has a very easy setup for using positional audio and adjusting volume based on distance, sometimes you’ll need a fine-grained
control to change sound properties during gameplay. Like other aspects of Godot, you can control audio via animations and scripting.
Controlling Audio via Animations
Changing audio properties via animations is the simplest way to trigge
r
audio effects and creating fade effects. Since they have great control
over nodes in the scene, they’re great for changing the properties of an
AudioStreamPlayer node, but animations can’t change global
properties like bus volumes and effects.
TRY IT YOURSELF
Animating Stream Player
Follow these steps from an empty scene to create an audio animation:
1. Add a
Node to serve as the root.
2. Create an
AudioStreamPlayer and set its stream to a song.
3. Add an
AnimationPlayer and create a new animation.
4. Set the animation to Autoplay on Load.
5. Change the length of the animation to 10 seconds.
6. Select the
AudioStreamPlayer node. In Inspector, click on the key button for the Play property to create a key frame.
Godot will ask if you want to create a track, so click on Create.
7. Go to the 1-second mark in the animation.
8. Enable the Play property and create another key frame.
9. Go to the 9-second mark in the animation.
10. Disable the Play property and create another key frame for it.
11. Go to the 3-second mark in the animation.
12. Create a track for the Volume dB property by clicking on its key button.
13. Go to the 5-second mark in the animation.
14. Set the Volume dB to -40 (negative forty) and create a key frame.
15. Create another key frame at the 6-second mark.
16. Go to the 8-second mark in the animation.
17. Set the Volume dB back to zero and make a key frame.
18. Save and play the scene. The sound will start playing, fade out, fade in again, then stop playing. While these step-by-step
111111111
22222222instructions may be convoluted, the steps in the Editor are simple and allow you to create powerful effects with ease.
Controlling Audio via Scripting
Animations are very powerful, but sometimes they are not enough. With scripting, you can get around that and do more than change volume
and trigger sounds.
If you use the AudioServer singleton, you can call functions that change the bus layout and all its properties. You can enable or disable
specific effects, change their values, or even add effects to the chain. It’s possible to change the volume of specific buses and replace the
target output. Check Godot’s documentation to see the available functions in the AudioServer class.
TIP
Tween Node
While you can’t use animations directly, the
Tween node can help you achieve similar effects when doing things via scripts. You can set
up interpolation for a bus volume or an effect parameter by using functions in the AudioServer singleton.
Summary
This hour explained the audio system inside the Godot engine. You learned how to play sounds directly to the output and how to make it vary
according to the object’s position, both in 2D and in 3D. You saw how to create and use buses, set up a bus chain, and add sound effects.
Finally, you learned how to change effects based on the audio source’s position.
Q&A
Q. How can I control audio latency?
A. Via the Output Latency property in Project Settings. Note that decreasing the value might cause buffering issues, which will be audible in
the form of clicks. You won’t generally have to use this setting unless you’re making time-sensitive games.
Q. Can Godot convert sound formats?
A. No. Godot supports only WAVE and Ogg Vorbis, and cannot convert files between formats. You can use free software such as Audacity to
convert audio files to a format supported byGodot.
Workshop
Let’s recall the contents of this hour by answering some questions.
Quiz
1. What are the nodes responsible for playing sounds?
2. True or False: Every audio played inGodot is affected by position.
3. How do you enable the Doppler effect?
4. True or False: It’s not possible to change audio properties during the game.
Answers
1. There are three:
AudioStreamPlayer,
AudioStreamPlayer2D, and
AudioStreamPlayer3D.
2. False. Sounds played with
AudioStreamPlayer won’t be affected by position (in fact, it does not even have a position).
3. Enable the Doppler Tracking property in the stream player node and on the
Camera.
4. False. Audio properties and effects can be changed via animation or via scripting.
Exercises
In this exercise, you will create a simple audio scene with Doppler and area effects.
1. Create a new scene and add a
Spatial node as the root. Save the scene.
2. Add a
MeshInstance node.
3. Set the Mesh property to a new
SphereMesh.
4. Add an
AudioStreamPlayer3D as a child of the
MeshInstance.
5. Set the Streamproperty to a song you have on your project. Enable the Autoplay property.
6. Create a
Camera node as a child of the root. Put it in a position to see the
MeshInstance.
111111111
222222227. Set the Doppler Tracking property of the camera to Fixed.
8. Do the same to the
AudioStreamPlayer3D node.
9. Create an
Area node as a child of the root.
10. Add a
CollisionShape as a child to the area.
11. Set the Shape property to a new
BoxShape. Set its values to (5, 5, 5).
12. Select the
MeshInstance node and set its Translation property to (0, 0, -50).
13. Open the Audio Bus Layout panel.
14. Create two new buses: FX and Reverb.
15. In the FX bus, add a LowPass effect. Set its cutoff frequency to 500 Hz and resonance to 1.
16. In the Reverb bus, add a Reverb effect. You can leave it with its default parameters.
17. Select the
Area node.
18. Enable the Audio Bus Override property and set the bus to “FX.”
19. Enable the Reverb Bus property. Set the name to “Reverb” and the amount to 1.
20. Add a script to the root node.
21. Set the script contents to the following code:
Click here to view code image
extends Spatial
export var speed = 10.0
func_process(delta):
$MeshInstance.translation += speed delta Vector3(0, 0, 1)
22. Save and play the scene. Use headphones or a surround setup to hear the sounds better. Notice how the audio changes based on the
position. The Doppler effect can be noticed by a change in pitch when the node passes through the camera. Also note the reverb and
low-pass effect when the ball passes within the area.
111111111
22222222