class_name AudioFader extends Node const DEFAULT_FADE = 0.25 const MUTE_VOLUME: float = -20.0 func _ready() -> void: process_mode = PROCESS_MODE_ALWAYS func fade_in( audio: AudioStreamPlayer, duration: float = DEFAULT_FADE, target: float = 0.0 ) -> void: audio.play() audio.volume_db = MUTE_VOLUME var dbps: float = (-MUTE_VOLUME - target)/duration while audio.volume_db < target: audio.volume_db += dbps*(await Wait.tick()) audio.volume_db = target func fade_out( audio: AudioStreamPlayer, duration: float = DEFAULT_FADE ) -> void: var dbps: float = (audio.volume_db - MUTE_VOLUME)/duration while audio.volume_db > MUTE_VOLUME: audio.volume_db -= dbps*(await Wait.tick()) audio.stop() audio.volume_db = 0.0 func cross_fade( stop: AudioStreamPlayer, start: AudioStreamPlayer, duration: float = DEFAULT_FADE, target: float = 0.0 ) -> void: var dbps_out: float = (stop.volume_db + 20.0)/duration var dbps_in: float = (-MUTE_VOLUME - target)/duration start.play() start.volume_db = MUTE_VOLUME while stop.volume_db > MUTE_VOLUME or start.volume_db < target: var delta: float = await Wait.tick() if stop.volume_db > MUTE_VOLUME: stop.volume_db -= delta*dbps_out else: stop.stop() if start.volume_db < target: start.volume_db += delta*dbps_in stop.volume_db = 0.0 start.volume_db = target