feat: add safe optional audio playback

This commit is contained in:
goose
2026-10-03 23:55:34 -04:00
parent d3c417fb91
commit efcaef181b
11 changed files with 339 additions and 54 deletions
@@ -0,0 +1,54 @@
class_name AudioImportManifest
extends Resource
## A deliberately small, Godot-native audio catalog.
##
## AudioLibrary only consumes AudioStream instances registered here. It never
## searches a user directory or asks an arbitrary file path to be decoded.
## A setup tool may construct this resource from assets already imported by
## Godot, then save it at USER_MANIFEST_PATH for the game to load.
const AMBIENCE_CONTEXTS := [&"exploration", &"combat", &"danger"]
const SFX_EVENTS := [&"attack_given", &"attack_received", &"menu_select", &"menu_cancel", &"item_use", &"death"]
const USER_AUDIO_DIRECTORY := "user://audio"
const USER_MANIFEST_PATH := "user://audio/audio_import_manifest.tres"
var ambience_streams: Dictionary = {}
var sfx_streams: Dictionary = {}
func register_ambience(context: StringName, stream: AudioStream) -> bool:
if not context in AMBIENCE_CONTEXTS or stream == null:
return false
ambience_streams[context] = stream
return true
func register_sfx(event: StringName, stream: AudioStream) -> bool:
if not event in SFX_EVENTS or stream == null:
return false
sfx_streams[event] = stream
return true
func ambience_for(context: StringName) -> AudioStream:
return ambience_streams.get(context) as AudioStream
func sfx_for(event: StringName) -> AudioStream:
return sfx_streams.get(event) as AudioStream
static func ensure_user_audio_directory() -> Error:
return DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(USER_AUDIO_DIRECTORY))
static func save_user_manifest(manifest: AudioImportManifest) -> Error:
if manifest == null:
return ERR_INVALID_PARAMETER
var directory_result := ensure_user_audio_directory()
if directory_result != OK:
return directory_result
return ResourceSaver.save(manifest, USER_MANIFEST_PATH)
static func load_user_manifest() -> AudioImportManifest:
if not FileAccess.file_exists(USER_MANIFEST_PATH):
return AudioImportManifest.new()
var resource := ResourceLoader.load(USER_MANIFEST_PATH, "AudioImportManifest", ResourceLoader.CACHE_MODE_IGNORE)
if resource is AudioImportManifest:
return resource as AudioImportManifest
return AudioImportManifest.new()
@@ -0,0 +1 @@
uid://bpu2ji542yhob
+105 -33
View File
@@ -1,30 +1,58 @@
class_name AudioLibrary
extends Node
const AudioImportManifestType = preload("res://scripts/infrastructure/audio_import_manifest.gd")
const AMBIENCE_CONTEXTS := ["exploration", "combat", "danger"]
const SFX_EVENTS := ["attack_given", "attack_received", "menu_select", "menu_cancel", "item_use", "death"]
const ADMITTED_EXTENSIONS := ["mp3", "ogg", "oga", "wav", "flac", "m4a", "opus"]
const DEFAULT_AUDIO_HOME := ".local/share/dcwascii"
const AMBIENCE_BUS := &"Ambience"
const SFX_BUS := &"SFX"
const DEFAULT_VOLUME_PERCENT := 100
const VOLUME_STEP_PERCENT := 10
var current_ambience_context := ""
var _audio_home_override := ""
var _manifest: AudioImportManifest
var _ambience_player: AudioStreamPlayer
var _sfx_player: AudioStreamPlayer
var _ambience_volume_percent := DEFAULT_VOLUME_PERCENT
var _sfx_volume_percent := DEFAULT_VOLUME_PERCENT
var _last_ambience_path := ""
var _last_sfx_path := ""
func _init(audio_home_override: String = "") -> void:
_audio_home_override = audio_home_override
func _init(manifest_or_legacy_root: Variant = null) -> void:
# The former API accepted an external directory override. Intentionally ignore
# it for compatibility: external paths are not a safe playback source.
if manifest_or_legacy_root is AudioImportManifest:
_manifest = manifest_or_legacy_root as AudioImportManifest
else:
_manifest = AudioImportManifestType.load_user_manifest()
func _ready() -> void:
_ensure_players()
func set_manifest(manifest: AudioImportManifest) -> void:
_manifest = manifest if manifest != null else AudioImportManifestType.new()
if current_ambience_context.is_empty():
_last_ambience_path = ""
else:
_set_ambience_stream(_manifest.ambience_for(StringName(current_ambience_context)))
func set_ambience_context(context: String) -> void:
if not context in AMBIENCE_CONTEXTS:
return
current_ambience_context = context
_last_ambience_path = _find_first_audio_file("audio", current_ambience_context)
_last_ambience_path = ""
_set_ambience_stream(_manifest.ambience_for(StringName(context)))
func play_sfx(event: String) -> void:
_last_sfx_path = ""
if not event in SFX_EVENTS:
return
_last_sfx_path = _find_first_audio_file("sfx", event)
_ensure_players()
var stream := _manifest.sfx_for(StringName(event))
_sfx_player.stream = stream
if stream != null:
_sfx_player.play()
func get_last_ambience_path() -> String:
return _last_ambience_path
@@ -32,34 +60,78 @@ func get_last_ambience_path() -> String:
func get_last_sfx_path() -> String:
return _last_sfx_path
func get_ambience_stream() -> AudioStream:
_ensure_players()
return _ambience_player.stream
func get_sfx_stream() -> AudioStream:
_ensure_players()
return _sfx_player.stream
func get_ambience_player() -> AudioStreamPlayer:
_ensure_players()
return _ambience_player
func get_sfx_player() -> AudioStreamPlayer:
_ensure_players()
return _sfx_player
func has_playable_ambience() -> bool:
return false
return get_ambience_stream() != null
func has_playable_sfx() -> bool:
return false
return get_sfx_stream() != null
func _audio_roots() -> Array[String]:
if not _audio_home_override.is_empty():
return [_audio_home_override]
var roots: Array[String] = []
var environment_root := OS.get_environment("DCW_AUDIO_HOME")
if not environment_root.is_empty():
roots.append(environment_root)
roots.append(OS.get_environment("HOME").path_join(DEFAULT_AUDIO_HOME))
return roots
func set_ambience_volume_percent(percent: int) -> void:
_ambience_volume_percent = clampi(percent, 0, 100)
_apply_volume(AMBIENCE_BUS, _ambience_volume_percent)
func _find_first_audio_file(kind: String, name: String) -> String:
for root in _audio_roots():
var directory_path := root.path_join(kind).path_join(name)
var directory := DirAccess.open(directory_path)
if directory == null:
continue
directory.list_dir_begin()
var entry := directory.get_next()
while not entry.is_empty():
if not directory.current_is_dir() and entry.get_extension().to_lower() in ADMITTED_EXTENSIONS:
directory.list_dir_end()
return directory_path.path_join(entry)
entry = directory.get_next()
directory.list_dir_end()
return ""
func set_sfx_volume_percent(percent: int) -> void:
_sfx_volume_percent = clampi(percent, 0, 100)
_apply_volume(SFX_BUS, _sfx_volume_percent)
func get_ambience_volume_percent() -> int:
return _ambience_volume_percent
func get_sfx_volume_percent() -> int:
return _sfx_volume_percent
func _set_ambience_stream(stream: AudioStream) -> void:
_ensure_players()
_ambience_player.stream = stream
if stream != null:
_ambience_player.play()
func _ensure_players() -> void:
if _ambience_player == null:
_ambience_player = AudioStreamPlayer.new()
_ambience_player.name = "AmbiencePlayer"
_ambience_player.bus = AMBIENCE_BUS
_ambience_player.finished.connect(_restart_ambience)
add_child(_ambience_player)
if _sfx_player == null:
_sfx_player = AudioStreamPlayer.new()
_sfx_player.name = "SfxPlayer"
_sfx_player.bus = SFX_BUS
add_child(_sfx_player)
_apply_volume(AMBIENCE_BUS, _ambience_volume_percent)
_apply_volume(SFX_BUS, _sfx_volume_percent)
func _restart_ambience() -> void:
if _ambience_player.stream != null:
_ambience_player.play()
func _apply_volume(bus_name: StringName, percent: int) -> void:
var bus_index := AudioServer.get_bus_index(bus_name)
if bus_index == -1:
bus_index = _ensure_bus(bus_name)
AudioServer.set_bus_volume_db(bus_index, linear_to_db(float(percent) / 100.0) if percent > 0 else -80.0)
func _ensure_bus(bus_name: StringName) -> int:
var existing_index := AudioServer.get_bus_index(bus_name)
if existing_index != -1:
return existing_index
AudioServer.add_bus()
var bus_index := AudioServer.bus_count - 1
AudioServer.set_bus_name(bus_index, bus_name)
return bus_index
+15 -2
View File
@@ -10,6 +10,7 @@ var ui_scale := 1.0
var _selected_index := 0
var _waiting_for_rebind := false
var _bindings: Dictionary[StringName, Key] = {}
var _audio_library: AudioLibrary
var waiting_for_rebind: bool:
get:
@@ -24,6 +25,7 @@ func _ready() -> void:
func present() -> void:
visible = true
_waiting_for_rebind = false
_audio_library = get_node_or_null("../../AudioLibrary") as AudioLibrary
refresh()
func dismiss() -> void:
@@ -44,7 +46,15 @@ func handle_key(event: InputEventKey) -> bool:
_waiting_for_rebind = false
refresh()
return true
if event.keycode == KEY_UP:
if event.keycode == KEY_A and _audio_library != null:
_audio_library.set_ambience_volume_percent(_audio_library.get_ambience_volume_percent() - AudioLibrary.VOLUME_STEP_PERCENT)
elif event.keycode == KEY_Z and _audio_library != null:
_audio_library.set_ambience_volume_percent(_audio_library.get_ambience_volume_percent() + AudioLibrary.VOLUME_STEP_PERCENT)
elif event.keycode == KEY_S and _audio_library != null:
_audio_library.set_sfx_volume_percent(_audio_library.get_sfx_volume_percent() - AudioLibrary.VOLUME_STEP_PERCENT)
elif event.keycode == KEY_X and _audio_library != null:
_audio_library.set_sfx_volume_percent(_audio_library.get_sfx_volume_percent() + AudioLibrary.VOLUME_STEP_PERCENT)
elif event.keycode == KEY_UP:
_selected_index = posmod(_selected_index - 1, 3)
elif event.keycode == KEY_DOWN:
_selected_index = posmod(_selected_index + 1, 3)
@@ -67,7 +77,9 @@ func refresh() -> void:
return
var cursor := func(index: int) -> String: return "> " if index == _selected_index else " "
var contrast := "Renforcé" if _selected_index == 1 else "Standard"
body.text = "%sÉchelle UI : %d%%\n%sMarqueurs color-blind : %s\n%sRemapper Inventaire : %s\n\nFlèches — ajuster Entrée — sélectionner Échap / O — fermer" % [cursor.call(0), int(ui_scale * 100.0), cursor.call(1), contrast, cursor.call(2), OS.get_keycode_string(binding_for(&"inventory"))]
var ambience_volume := _audio_library.get_ambience_volume_percent() if _audio_library != null else 100
var sfx_volume := _audio_library.get_sfx_volume_percent() if _audio_library != null else 100
body.text = "%sÉchelle UI : %d%%\n%sMarqueurs color-blind : %s\n%sRemapper Inventaire : %s\n\nAmbiance : %d%% Effets sonores : %d%%\nA / Z — volume ambiance S / X — volume effets\nFlèches — ajuster Entrée — sélectionner Échap / O — fermer" % [cursor.call(0), int(ui_scale * 100.0), cursor.call(1), contrast, cursor.call(2), OS.get_keycode_string(binding_for(&"inventory")), ambience_volume, sfx_volume]
func _adjust_selected(direction: int) -> void:
if _selected_index == 0:
@@ -75,6 +87,7 @@ func _adjust_selected(direction: int) -> void:
ui_scale = SCALE_STEPS[clampi(index + direction, 0, SCALE_STEPS.size() - 1)]
_apply_scale()
func _apply_scale() -> void:
var hud := get_parent() as CanvasLayer
if hud == null: