class_name SoundBoard extends Node ## Plays the theme's sounds: "roll" (a roll starts), "card_turn" (a Deck mode ## result is revealed), "thread" (a roll travels along a thread), "click" (a ## button is pressed) and "ambient" (loops while the theme is on). A theme ## without a sound for an event stays quiet. The volume is an app setting. const SETTING := "sound_volume" ## Volume levels for View ▾ → Sound: [label, linear volume]. const LEVELS := [["Off", 0.0], ["Quiet", 0.35], ["Medium", 0.65], ["Loud", 1.0]] const DEFAULT_VOLUME := 0.35 const EVENTS := ["roll", "card_turn", "thread", "click", "ambient"] ## Short sounds can overlap this many at a time. const VOICES := 4 var m: Main var volume := DEFAULT_VOLUME var _streams: Dictionary = {} var _voices: Array[AudioStreamPlayer] = [] var _next_voice := 0 var _ambient: AudioStreamPlayer func _init(p_main: Main) -> void: m = p_main name = "SoundBoard" if m.state: volume = clampf(float(m.state.get_setting(SETTING, DEFAULT_VOLUME)), 0.0, 1.0) var sounds: Dictionary = ThemeStore.current.get("sounds", {}) for event: String in EVENTS: var stream := ThemeAssets.sound(ThemeStore.current, str(sounds.get(event, ""))) if stream: _streams[event] = stream for i in VOICES: var voice := AudioStreamPlayer.new() _voices.append(voice) add_child(voice) _ambient = AudioStreamPlayer.new() add_child(_ambient) func _ready() -> void: if _streams.has("click"): get_tree().node_added.connect(_hook_button) _start_ambient() func has(event: String) -> bool: return _streams.has(event) func play(event: String) -> void: if volume <= 0.0 or not _streams.has(event) or event == "ambient": return var voice := _voices[_next_voice] _next_voice = (_next_voice + 1) % VOICES voice.stream = _streams[event] voice.volume_db = linear_to_db(volume) voice.play() func set_volume(level: float) -> void: volume = clampf(level, 0.0, 1.0) if m.state: m.state.set_setting(SETTING, volume) m.state.save() _start_ambient() ## The label of the level closest to the current volume. func level_name() -> String: var best: Array = LEVELS[0] for level: Array in LEVELS: if absf(float(level[1]) - volume) < absf(float(best[1]) - volume): best = level return str(best[0]) func _start_ambient() -> void: if not _streams.has("ambient") or volume <= 0.0: _ambient.stop() return var stream: AudioStream = _streams["ambient"] if "loop" in stream: stream.set("loop", true) _ambient.stream = stream _ambient.volume_db = linear_to_db(volume * 0.5) if not _ambient.playing: _ambient.play() func _hook_button(node: Node) -> void: var button := node as BaseButton if button and not button.pressed.is_connected(play): button.pressed.connect(play.bind("click"))