Tiny Shelf 33 · Add a gentle shelf chime

Tiny Shelf Studio · Lesson 33 of 50 · Intermediate to advanced · About 35 min

A fitted package deserves a soft click. Give a blocked move a lower tone and a message, so the sound confirms what the player already sees.

Miniature packaging workshop with coloured paper models, tools and a teal cutting mat.
What you’ll make Build two short sound cues and show matching text so mute still works.

Download the projects from the course page. In Godot’s Project Manager, choose Import, select project.godot, and use Run Project (F5). Start from checkpoints/32 when the lesson builds on prior work, or copy the checkpoints/33 folder to try this lesson on its own. Read the file names in the steps before editing.

Build two tones. Choose a higher and lower pitch. → Read action result. Tell the player what happened. → Check mute. Skip sound while muted. → Play one cue. Load the matching sound.
Build two tones → Read action result → Check mute → Play one cue
Godot checkpoint window for Add a gentle shelf chime
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson AudioStreamWAV, PackedByteArray, sin, TAU, toggle_mode, AudioStreamPlayer.

  1. Open the design bench

    Import this checkpoint's project.godot into Godot 4.7.2. Open main.gd from FileSystem. Press F5 for the starting view and F8 to stop it. Keep a copy to undo experiments.

    Why it works The checkpoint scene attaches main.gd to a Control. Each test starts from that known version, so compare one change with the original.

  2. Create the sound player

    Find AudioStreamPlayer.new and add_child(player) in _ready. Follow where this same player is used when you try the two actions.

    player = AudioStreamPlayer.new()

    Why it works One audio player can play either short cue. add_child puts it in the active scene so Godot can play it.

  3. Choose two pitches

    Compare the accept and blocked build_tone calls. Change 660.0 to 520.0 and run. That cue should sound lower than before.

    accept_tone = build_tone(660.0)

    Why it works Frequency counts cycles per second. Increasing it raises the pitch. The second frequency remains the lower one.

  4. Write a small sound buffer

    Read frames and resize. Test a LENGTH of 0.20 for both buttons. Compare how long the sound takes without increasing its volume.

    samples.resize(frames * 2)

    Why it works Each frame stores one 16-bit sample, which takes two bytes. The sample rate decides how quickly Godot plays them.

  5. Soften the ends

    In the sample loop, follow the lift and fade multipliers. Put fade = 1.0 temporarily and listen at comfortable volume for a sharper ending, then restore.

    var wave_sample := int(4200.0 * sin(phase) * fade * lift)

    Why it works The sample starts near zero and gets quieter toward the end. Smooth edges reduce a click when a short cue begins or ends.

  6. Protect the silent path

    Turn sound off, then press the two test actions. Read both messages. Follow the condition that lets text update and skips playback.

    if not mute.button_pressed:

    Why it works button_pressed is a Boolean. The condition only wraps the audio work, leaving the written feedback available.

Watch the values change

  1. Fit a package fitted is true and sound is on.
    What you see. The higher cue plays and the message says Placed.
  2. Try blocked slot fitted is false.
    What you see. The lower cue plays and the message says Blocked.
  3. Mute and fit again mute.button_pressed is true.
    What you see. The result is still readable and there is no tone.

Predict before you run Does turning sound off prevent the package action from being understood?

Reveal the answer

No. status.text updates before the audio condition. The cue is one of two ways to confirm the result.

Complete checkpoint

Two written shelf results and two gentle test cues, with a mute switch that stops and skips audio.

main.gd

extends Control

const SAMPLE_RATE := 22050
const LENGTH := 0.15
var accept_tone: AudioStreamWAV
var blocked_tone: AudioStreamWAV
var player: AudioStreamPlayer
var mute: Button
var status: Label
var ok_move := false

func _ready() -> void:
	title_page("SOUND", "Add a gentle shelf chime", "Keep feedback readable when your phone is muted.")
	player = AudioStreamPlayer.new()
	add_child(player)
	accept_tone = build_tone(660.0)
	blocked_tone = build_tone(235.0)
	status = label("Choose an action to hear its cue.", Vector2(66, 240), 25)
	place_button("Fit a package", Vector2(66, 370), feedback.bind(true))
	place_button("Try blocked slot", Vector2(252, 370), feedback.bind(false), 185)
	mute = place_button("Sound: on", Vector2(625, 370), update_mute)
	mute.toggle_mode = true

func build_tone(frequency: float) -> AudioStreamWAV:
	var clip := AudioStreamWAV.new()
	var samples := PackedByteArray()
	var frames := int(SAMPLE_RATE * LENGTH)
	samples.resize(frames * 2)
	for i in range(frames):
		var phase := TAU * frequency * float(i) / SAMPLE_RATE
		var lift := minf(float(i) / 110.0, 1.0)
		var fade := 1.0 - float(i) / frames
		var wave_sample := int(4200.0 * sin(phase) * fade * lift)
		samples.encode_s16(i * 2, wave_sample)
	clip.format = AudioStreamWAV.FORMAT_16_BITS
	clip.mix_rate = SAMPLE_RATE
	clip.data = samples
	return clip

func update_mute() -> void:
	mute.text = "Sound: off" if mute.button_pressed else "Sound: on"
	if mute.button_pressed:
		player.stop()

func feedback(fitted: bool) -> void:
	ok_move = fitted
	status.text = "Placed · the package fits." if fitted else "Blocked · that slot is occupied."
	if not mute.button_pressed:
		player.stream = accept_tone if fitted else blocked_tone
		player.play()
	queue_redraw()

func _draw() -> void:
	backdrop()
	var edge := SEA if ok_move else GOLD
	panel(Rect2(49, 191, 852, 138), Color("#244457"), edge)

const PAPER := Color("#fff4de")
const GOLD := Color("#f5bd79")
const SEA := Color("#9ddcd0")
const INK := Color("#172c3c")
const EDGE := Color("#54817f")

func title_page(unit: String, heading: String, subtitle: String) -> void:
	label("TINY SHELF STUDIO  /  " + unit, Vector2(44, 36), 14, GOLD)
	label(heading, Vector2(44, 65), 33)
	label(subtitle, Vector2(46, 119), 16, SEA)

func label(words: String, at: Vector2, pixels: int = 20, ink: Color = PAPER) -> Label:
	var item := Label.new()
	item.text = words
	item.position = at
	item.add_theme_font_size_override("font_size", pixels)
	item.add_theme_color_override("font_color", ink)
	add_child(item)
	return item

func place_button(words: String, at: Vector2, action: Callable, width: float = 170.0) -> Button:
	var control := Button.new()
	control.text = words
	control.position = at
	control.custom_minimum_size = Vector2(width, 48)
	control.add_theme_font_size_override("font_size", 17)
	control.add_theme_color_override("font_color", PAPER)
	control.add_theme_stylebox_override("normal", style(Color("#244557"), EDGE))
	control.add_theme_stylebox_override("hover", style(Color("#365a62"), SEA))
	control.add_theme_stylebox_override("pressed", style(Color("#315b56"), SEA))
	control.add_theme_stylebox_override("focus", style(Color.TRANSPARENT, GOLD, 3))
	control.pressed.connect(action)
	add_child(control)
	return control

func style(fill: Color, edge: Color, line: int = 1) -> StyleBoxFlat:
	var block := StyleBoxFlat.new()
	block.bg_color = fill
	block.border_color = edge
	block.set_border_width_all(line)
	block.set_corner_radius_all(8)
	return block

func panel(rect: Rect2, fill: Color, edge: Color = EDGE) -> void:
	draw_style_box(style(fill, edge), rect)

func backdrop() -> void:
	draw_rect(Rect2(Vector2.ZERO, size), Color("#102333"))
	panel(Rect2(22, 19, size.x - 44, size.y - 38), Color("#183344"), Color("#325665"))

func paint_words(words: String, at: Vector2, pixels: int = 16, ink: Color = PAPER) -> void:
	draw_string(ThemeDB.fallback_font, at, words, HORIZONTAL_ALIGNMENT_LEFT, -1, pixels, ink)

GDScript line by line

Follow the line numbers, including the indent at the start of each line. Find the code the game will run first, then look for the function that reacts when you tap or change something.

Read main.gd line by line
  1. extends ControlStarts with Godot's Control type. This script gets the abilities of that type and adds the game's own rules.
  2. const SAMPLE_RATE := 22050This number tells Godot how many audio samples make one second.
  3. const LENGTH := 0.15The fraction is measured in seconds. Lower it for an even shorter cue.
  4. var accept_tone: AudioStreamWAVDeclares accept_tone for later use. A colon followed by a type says which kind of value belongs here.
  5. var blocked_tone: AudioStreamWAVDeclares blocked_tone for later use. A colon followed by a type says which kind of value belongs here.
  6. var player: AudioStreamPlayerDeclares player for later use. A colon followed by a type says which kind of value belongs here.
  7. var mute: ButtonDeclares mute for later use. A colon followed by a type says which kind of value belongs here.
  8. var status: LabelDeclares status for later use. A colon followed by a type says which kind of value belongs here.
  9. var ok_move := falseCreates a variable named ok_move. The expression uses the yes-or-no value false. Godot infers the type from the first value.
  10. func _ready() -> void:Godot calls this once after the scene and its children are ready. Use it to set up the room and connect controls.
  11. title_page("SOUND", "Add a gentle shelf chime", "Keep feedback readable when your phone is muted.")Calls title_page with the values in its parentheses.
  12. player = AudioStreamPlayer.new()Stores the new value in player. The expression creates a new AudioStreamPlayer object.
  13. add_child(player)Adds the new node to the scene tree so that Godot can run and draw it.
  14. accept_tone = build_tone(660.0)Stores the new value in accept_tone. The expression calls build_tone with the values in its parentheses.
  15. blocked_tone = build_tone(235.0)Stores the new value in blocked_tone. The expression calls build_tone with the values in its parentheses.
  16. status = label("Choose an action to hear its cue.", Vector2(66, 240), 25)Stores the new value in status. The expression calls label with the values in its parentheses.
  17. place_button("Fit a package", Vector2(66, 370), feedback.bind(true))Calls place_button with the values in its parentheses.
  18. place_button("Try blocked slot", Vector2(252, 370), feedback.bind(false), 185)Calls place_button with the values in its parentheses.
  19. mute = place_button("Sound: on", Vector2(625, 370), update_mute)Stores the new value in mute. The expression calls place_button with the values in its parentheses.
  20. mute.toggle_mode = trueThe mute control holds its pressed state until the next press, like a switch.
  21. func build_tone(frequency: float) -> AudioStreamWAV:Defines build tone, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  22. var clip := AudioStreamWAV.new()Creates a variable named clip. The expression creates a new AudioStreamWAV object. Godot infers the type from the first value.
  23. var samples := PackedByteArray()Creates a variable named samples. The expression calls PackedByteArray with the values in its parentheses. Godot infers the type from the first value.
  24. var frames := int(SAMPLE_RATE * LENGTH)Multiply seconds by samples per second, then convert to a whole number of samples.
  25. samples.resize(frames * 2)Reserve two bytes per sample so every 16-bit number has its own space.
  26. for i in range(frames):Repeats the indented instructions for each value in range(frames).
  27. var phase := TAU * frequency * float(i) / SAMPLE_RATEConvert this frame into a time and multiply by frequency and a full rotation, TAU.
  28. var lift := minf(float(i) / 110.0, 1.0)Start the wave near silent and bring it up for the first 110 samples. minf caps the multiplier at one.
  29. var fade := 1.0 - float(i) / framesAs the sample index approaches the end, bring the volume down toward zero.
  30. var wave_sample := int(4200.0 * sin(phase) * fade * lift)Creates a variable named wave_sample. The expression converts a suitable value to a whole number. Godot infers the type from the first value.
  31. samples.encode_s16(i * 2, wave_sample)Write one signed sixteen-bit sample, two bytes at a time.
  32. clip.format = AudioStreamWAV.FORMAT_16_BITSStores the new value in clip.format. The expression reads AudioStreamWAV.FORMAT_16_BITS.
  33. clip.mix_rate = SAMPLE_RATEUse the same sample rate at playback so the duration and pitch match the calculation.
  34. clip.data = samplesStores the new value in clip.data. The expression reads samples.
  35. return clipFinishes the function and hands its result back to the caller. The expression reads clip.
  36. func update_mute() -> void:Defines update mute, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  37. mute.text = "Sound: off" if mute.button_pressed else "Sound: on"Updates mute.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle.
  38. if mute.button_pressed:Checks mute.button_pressed. The indented instructions below run only if this test passes.
  39. player.stop()A cue already playing should stop when mute is switched on.
  40. func feedback(fitted: bool) -> void:Defines feedback, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  41. ok_move = fittedStores the new value in ok_move. The expression reads fitted.
  42. status.text = "Placed · the package fits." if fitted else "Blocked · that slot is occupied."Always write this feedback before checking mute.
  43. if not mute.button_pressed:Checks not mute.button_pressed. The indented instructions below run only if this test passes.
  44. player.stream = accept_tone if fitted else blocked_toneSelect a clip by result and play it through the one shared audio node.
  45. player.play()Starts this sound or animation.
  46. queue_redraw()Asks Godot to call _draw again on a later frame so the screen matches the new state.
  47. func _draw() -> void:Godot calls this when the node needs drawing. The instructions inside paint the current state.
  48. backdrop()Calls backdrop with the values in its parentheses.
  49. var edge := SEA if ok_move else GOLDCreates a variable named edge. The expression chooses one of two values by checking the condition in the middle. Godot infers the type from the first value.
  50. panel(Rect2(49, 191, 852, 138), Color("#244457"), edge)Calls panel with the values in its parentheses.
  51. const PAPER := Color("#fff4de")Creates a constant named PAPER. The expression builds a colour from these values. Godot infers the type from the first value.
  52. const GOLD := Color("#f5bd79")Creates a constant named GOLD. The expression builds a colour from these values. Godot infers the type from the first value.
  53. const SEA := Color("#9ddcd0")Creates a constant named SEA. The expression builds a colour from these values. Godot infers the type from the first value.
  54. const INK := Color("#172c3c")Creates a constant named INK. The expression builds a colour from these values. Godot infers the type from the first value.
  55. const EDGE := Color("#54817f")Creates a constant named EDGE. The expression builds a colour from these values. Godot infers the type from the first value.
  56. func title_page(unit: String, heading: String, subtitle: String) -> void:Defines title page, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  57. label("TINY SHELF STUDIO / " + unit, Vector2(44, 36), 14, GOLD)Make a small line above the main heading so you can tell which checkpoint is open.
  58. label(heading, Vector2(44, 65), 33)Calls label with the values in its parentheses.
  59. label(subtitle, Vector2(46, 119), 16, SEA)Calls label with the values in its parentheses.
  60. func label(words: String, at: Vector2, pixels: int = 20, ink: Color = PAPER) -> Label:Defines label, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  61. var item := Label.new()Creates a variable named item. The expression creates a new Label object. Godot infers the type from the first value.
  62. item.text = wordsUpdates item.text, which controls the words a player sees. The expression reads words.
  63. item.position = atUpdates item.position, which controls the node's local x and y location. The expression reads at.
  64. item.add_theme_font_size_override("font_size", pixels)This Label has its own readable type size. Changing that value leaves the other labels alone.
  65. item.add_theme_color_override("font_color", ink)This label keeps the chosen text ink even when the default theme changes.
  66. add_child(item)Adds the new node to the scene tree so that Godot can run and draw it.
  67. return itemFinishes the function and hands its result back to the caller. The expression reads item.
  68. func place_button(words: String, at: Vector2, action: Callable, width: float = 170.0) -> Button:Defines place button, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  69. var control := Button.new()Creates a variable named control. The expression creates a new Button object. Godot infers the type from the first value.
  70. control.text = wordsUpdates control.text, which controls the words a player sees. The expression reads words.
  71. control.position = atUpdates control.position, which controls the node's local x and y location. The expression reads at.
  72. control.custom_minimum_size = Vector2(width, 48)Give the button room for its label and an easy target for taps. Containers and layouts can allocate more space.
  73. control.add_theme_font_size_override("font_size", 17)Calls control.add_theme_font_size_override with the values in its parentheses.
  74. control.add_theme_color_override("font_color", PAPER)Calls control.add_theme_color_override with the values in its parentheses.
  75. control.add_theme_stylebox_override("normal", style(Color("#244557"), EDGE))Calls control.add_theme_stylebox_override with the values in its parentheses.
  76. control.add_theme_stylebox_override("hover", style(Color("#365a62"), SEA))Calls control.add_theme_stylebox_override with the values in its parentheses.
  77. control.add_theme_stylebox_override("pressed", style(Color("#315b56"), SEA))Calls control.add_theme_stylebox_override with the values in its parentheses.
  78. control.add_theme_stylebox_override("focus", style(Color.TRANSPARENT, GOLD, 3))Draw a gold outline around keyboard focus. Other button styles can still indicate hover and press independently.
  79. control.pressed.connect(action)pressed fires on a successful control activation. Godot calls the function passed in without running it at setup time.
  80. add_child(control)Adds the new node to the scene tree so that Godot can run and draw it.
  81. return controlFinishes the function and hands its result back to the caller. The expression reads control.
  82. func style(fill: Color, edge: Color, line: int = 1) -> StyleBoxFlat:Defines style, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  83. var block := StyleBoxFlat.new()Creates a variable named block. The expression creates a new StyleBoxFlat object. Godot infers the type from the first value.
  84. block.bg_color = fillStores the new value in block.bg_color. The expression reads fill.
  85. block.border_color = edgeStores the new value in block.border_color. The expression reads edge.
  86. block.set_border_width_all(line)Apply one border line width to all four edges of the card.
  87. block.set_corner_radius_all(8)Round each corner of this reusable style by eight pixels.
  88. return blockFinishes the function and hands its result back to the caller. The expression reads block.
  89. func panel(rect: Rect2, fill: Color, edge: Color = EDGE) -> void:Defines panel, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  90. draw_style_box(style(fill, edge), rect)Calls draw_style_box with the values in its parentheses.
  91. func backdrop() -> void:Defines backdrop, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  92. draw_rect(Rect2(Vector2.ZERO, size), Color("#102333"))Paints a rectangle at the given position and size.
  93. panel(Rect2(22, 19, size.x - 44, size.y - 38), Color("#183344"), Color("#325665"))Subtract space on both sides of the canvas. As the window changes, the outer frame fits within it.
  94. func paint_words(words: String, at: Vector2, pixels: int = 16, ink: Color = PAPER) -> void:Defines paint words, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  95. draw_string(ThemeDB.fallback_font, at, words, HORIZONTAL_ALIGNMENT_LEFT, -1, pixels, ink)Godot draws the words from the baseline at the supplied pixel position using its fallback typeface.

Find and fix a bug

If a tone sounds harsh, reduce its amplitude first and check the fade and lift multipliers. Tone height and loudness are different.

Try a change

Give a completed shelf a distinct third cue. Write the text for it before you wire up the sound.