Loading...
Loading...
Play and mix audio in Godot 4.x: AudioStreamPlayer (2D/3D variants), audio buses with volume/mute and effects, music vs SFX routing, db/linear volume, and precise sync-to-beat playback timing. Use when playing sounds or music in a Godot project, routing AudioStreamPlayer nodes to buses, adjusting bus volume via AudioServer, or syncing gameplay to the beat.
npx skill4agent add gamedev-skills/awesome-gamedev-agent-skills godot-audioaudio-designAudioStreamPlayerAudioStreamPlayer2DAudioStreamPlayer3DAudioStreamstream.ogg.wavplay()autoplaybus"Music""SFX"0 dB-80 dBlinear_to_dbdb_to_linearAudioServer@onready var sfx: AudioStreamPlayer = $Sfx # stream assigned in the editor
func play_jump() -> void:
sfx.pitch_scale = randf_range(0.95, 1.05) # slight variation avoids fatigue
sfx.play()
# For many overlapping copies, use an AudioStreamPlayer with an
# AudioStreamPolyphonic stream, or spawn short-lived players and free on `finished`.func set_music_volume(linear_0_to_1: float) -> void:
var bus := AudioServer.get_bus_index("Music")
# Convert a 0..1 slider to decibels; clamp avoids -inf at 0.
AudioServer.set_bus_volume_db(bus, linear_to_db(maxf(linear_0_to_1, 0.0001)))
func toggle_sfx(muted: bool) -> void:
AudioServer.set_bus_mute(AudioServer.get_bus_index("SFX"), muted)@onready var a: AudioStreamPlayer = $MusicA
@onready var b: AudioStreamPlayer = $MusicB
func crossfade_to(stream: AudioStream, secs := 1.5) -> void:
b.stream = stream
b.volume_db = -40.0
b.play()
var tw := create_tween().set_parallel(true)
tw.tween_property(a, "volume_db", -40.0, secs) # fade out current
tw.tween_property(b, "volume_db", 0.0, secs) # fade in next
tw.chain().tween_callback(a.stop)
var tmp := a; a = b; b = tmp # swap roles@onready var music: AudioStreamPlayer = $Music
func get_playback_time() -> float:
# Add time since the last audio mix, subtract output latency, for sub-frame accuracy.
var t := music.get_playback_position() + AudioServer.get_time_since_last_mix()
return t - AudioServer.get_output_latency()volume_dbset_bus_volume_dbvolume_db = 0.5linear_to_dblinear_to_db(0.0)-inf0.0001get_bus_index("Muisc")-1AudioStreamPolyphonicAudioStreamPlayerfinished.oggAudioStreamWAVloop_modeget_playback_position()get_time_since_last_mix()get_output_latency()AudioListener3DCamera3Dmax_distance.tresAudioStreamPolyphonicAudioStreamInteractiveAudioStreamGeneratorreferences/buses-and-effects.mdaudio-designgodot-animationget_playback_position()godot-ui-controlAudioServer