godot-audio

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Godot Audio (4.x)

Godot 音频(4.x版)

Play SFX and music, route them through buses, control volume in decibels, and time gameplay to the beat. Targets Godot 4.3+.
播放音效(SFX)和音乐,通过总线路由音频,以分贝为单位控制音量,并让游戏玩法与节拍同步。适用于**Godot 4.3+**版本。

When to use

使用场景

  • Use when playing sound effects or music, routing audio to buses (Master/Music/SFX), adjusting volume/mute from code, adding bus effects (reverb, compressor), positional 3D audio, or syncing events to music.
When not to use: engine-agnostic audio design (adaptive music structure, mixing philosophy, ducking patterns) →
audio-design
; importing/encoding assets outside Godot.
  • 适用于播放音效或音乐、将音频路由到总线(主总线/音乐总线/SFX总线)、通过代码调整音量/静音、添加总线效果(混响、压缩器)、3D定位音频,或让事件与音乐同步的场景。
不适用于: 引擎无关的音频设计(自适应音乐结构、混音理念、闪避模式)→ 参考
audio-design
;在Godot外部导入/编码资源。

Core workflow

核心工作流程

  1. Pick the player node:
    • AudioStreamPlayer
      — non-positional (music, UI, global SFX).
    • AudioStreamPlayer2D
      /
      AudioStreamPlayer3D
      — positional; volume/pan from distance.
  2. Assign an
    AudioStream
    to
    stream
    (
    .ogg
    for music/loops,
    .wav
    for short SFX) and
    play()
    . Set
    autoplay
    for music that starts with the scene.
  3. Route to a bus. Set the player's
    bus
    to a named bus (e.g.
    "Music"
    ,
    "SFX"
    ). Define buses in the Audio panel (bottom dock); each can have volume, mute, solo, and effects.
  4. Control volume in dB, not linear (audio is logarithmic).
    0 dB
    = unchanged,
    -80 dB
    ≈ silent. Convert with
    linear_to_db
    /
    db_to_linear
    .
  5. Drive volume/mute from code with
    AudioServer
    by bus index.
  6. For rhythm, compute precise playback time using output latency compensation.
  1. 选择播放器节点:
    • AudioStreamPlayer
      —— 非定位音频(音乐、UI音效、全局SFX)。
    • AudioStreamPlayer2D
      /
      AudioStreamPlayer3D
      —— 定位音频;音量/声像随距离变化。
  2. stream
    分配
    AudioStream
    (音乐/循环音效用
    .ogg
    ,短音效用
    .wav
    )并调用
    play()
    。若音乐需随场景启动自动播放,设置
    autoplay
  3. 路由到总线。 将播放器的
    bus
    设置为指定总线(如
    "Music"
    "SFX"
    )。在音频面板(底部 dock)中定义总线;每条总线可设置音量、静音、独奏和效果。
  4. 以分贝为单位控制音量,而非线性值(音频是对数特性)。
    0 dB
    = 原始音量,
    -80 dB
    ≈ 静音。使用
    linear_to_db
    /
    db_to_linear
    进行转换。
  5. 通过代码借助
    AudioServer
    控制音量/静音
    ,需使用总线索引。
  6. 实现节奏同步时,计算播放时间需补偿输出延迟。

Patterns

实践模式

1. One-shot SFX (fire-and-forget)

1. 一次性音效(触发即无需管)

gdscript
@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()
gdscript
@onready var sfx: AudioStreamPlayer = $Sfx   # 已在编辑器中分配stream

func play_jump() -> void:
    sfx.pitch_scale = randf_range(0.95, 1.05)   # 轻微音高变化避免听觉疲劳
    sfx.play()

For many overlapping copies, use an AudioStreamPlayer with an

若需多个重叠音效,使用带有AudioStreamPolyphonic流的AudioStreamPlayer,或生成短生命周期的播放器并在
finished
信号触发时释放。

AudioStreamPolyphonic stream, or spawn short-lived players and free on
finished
.

undefined
undefined

2. Set a bus's volume and mute via AudioServer

2. 通过AudioServer设置总线音量和静音

gdscript
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)
gdscript
func set_music_volume(linear_0_to_1: float) -> void:
    var bus := AudioServer.get_bus_index("Music")
    # 将0..1的滑块值转换为分贝;限制最小值避免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)

3. Crossfade between two music tracks

3. 两首音乐曲目交叉淡入淡出

gdscript
@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
gdscript
@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)   # 当前曲目淡出
    tw.tween_property(b, "volume_db", 0.0, secs)     # 下一曲目淡入
    tw.chain().tween_callback(a.stop)
    var tmp := a; a = b; b = tmp                      # 交换角色

4. Beat-accurate timing (compensate for output latency)

4. 节拍精准同步(补偿输出延迟)

gdscript
@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()
gdscript
@onready var music: AudioStreamPlayer = $Music

func get_playback_time() -> float:
    # 加上上次音频混音后的时间,减去输出延迟,实现亚帧精度。
    var t := music.get_playback_position() + AudioServer.get_time_since_last_mix()
    return t - AudioServer.get_output_latency()

Pitfalls

常见陷阱

  • Treating volume as linear.
    volume_db
    /
    set_bus_volume_db
    are decibels. Setting
    volume_db = 0.5
    is nearly full volume, not half. Map sliders with
    linear_to_db
    .
  • linear_to_db(0.0)
    is
    -inf
    .
    Clamp the linear value to a small minimum (e.g.
    0.0001
    ) before converting, or special-case 0 → mute.
  • Bus name typos fail quietly.
    get_bus_index("Muisc")
    returns
    -1
    ; calls then error or no-op. Match the exact bus name from the Audio panel.
  • Short SFX cut off when the same player is retriggered. Use separate players, an
    AudioStreamPolyphonic
    , or
    AudioStreamPlayer
    per-shot freed on
    finished
    .
  • Music doesn't loop unless the import/stream loop is enabled (
    .ogg
    import has a Loop option;
    AudioStreamWAV
    has
    loop_mode
    ).
  • Syncing to
    get_playback_position()
    alone is jittery
    — it updates per audio mix, not per frame; add
    get_time_since_last_mix()
    and subtract
    get_output_latency()
    .
  • 3D audio inaudible → no
    AudioListener3D
    /
    Camera3D
    to hear it, or
    max_distance
    / attenuation too tight, or wrong bus muted.
  • 将音量视为线性值。
    volume_db
    /
    set_bus_volume_db
    的单位是分贝。设置
    volume_db = 0.5
    几乎是满音量,而非一半。需用
    linear_to_db
    映射滑块值。
  • linear_to_db(0.0)
    结果为
    -inf
    转换前需将线性值限制为较小的最小值(如
    0.0001
    ),或对0值单独处理为静音。
  • 总线名称拼写错误会静默失败。
    get_bus_index("Muisc")
    返回
    -1
    ;后续调用会报错或无操作。需与音频面板中的总线名称完全匹配。
  • 短音效在同一播放器重复触发时被截断。 使用单独的播放器、
    AudioStreamPolyphonic
    ,或每次触发时生成一个
    AudioStreamPlayer
    并在
    finished
    时释放。
  • 音乐无法循环,除非导入/流的循环功能已启用(
    .ogg
    导入有Loop选项;
    AudioStreamWAV
    loop_mode
    )。
  • 仅使用
    get_playback_position()
    同步会有抖动
    ——它仅在每次音频混音时更新,而非每帧;需加上
    get_time_since_last_mix()
    并减去
    get_output_latency()
  • 3D音频听不到→ 缺少
    AudioListener3D
    /
    Camera3D
    作为监听者,或
    max_distance
    /衰减设置过严,或错误地静音了对应总线。

References

参考资料

  • For the bus layout (
    .tres
    ), adding effects (reverb/compressor/EQ) and side-chain ducking,
    AudioStreamPolyphonic
    /
    AudioStreamInteractive
    , microphone capture, and procedural audio with
    AudioStreamGenerator
    , read
    references/buses-and-effects.md
    .
  • 关于总线布局(
    .tres
    )、添加效果(混响/压缩器/均衡器)和侧链闪避、
    AudioStreamPolyphonic
    /
    AudioStreamInteractive
    、麦克风捕获,以及使用
    AudioStreamGenerator
    生成 procedural audio,可阅读
    references/buses-and-effects.md

Related skills

相关技能

  • audio-design
    — engine-agnostic adaptive music, mixing, and ducking practice.
  • godot-animation
    — syncing animation/Tween to
    get_playback_position()
    .
  • godot-ui-control
    — volume sliders wired to
    AudioServer
    .
  • audio-design
    —— 引擎无关的自适应音乐、混音和闪避实践。
  • godot-animation
    —— 将动画/Tween与
    get_playback_position()
    同步。
  • godot-ui-control
    —— 连接到
    AudioServer
    的音量滑块。