audio-and-sound

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Audio and Sound

音频与音效

Phaser provides a unified Sound system via
this.sound
(a SoundManager) that abstracts over Web Audio API and HTML5 Audio. It handles loading, playback, volume, panning, looping, markers, audio sprites, spatial audio, and browser autoplay-policy unlocking.
Key source paths:
src/sound/BaseSoundManager.js
,
src/sound/BaseSound.js
,
src/sound/webaudio/
,
src/sound/html5/
,
src/sound/SoundManagerCreator.js
,
src/sound/events/
,
src/sound/typedefs/
Related skills: ../loading-assets/SKILL.md, ../game-setup-and-config/SKILL.md
Phaser通过
this.sound
(一个SoundManager)提供统一的音效系统,它对Web Audio API和HTML5 Audio进行了抽象封装。该系统负责处理音频加载、播放、音量控制、声像定位、循环播放、标记点、音频精灵、空间音频以及浏览器自动播放策略解锁等功能。
核心源码路径:
src/sound/BaseSoundManager.js
,
src/sound/BaseSound.js
,
src/sound/webaudio/
,
src/sound/html5/
,
src/sound/SoundManagerCreator.js
,
src/sound/events/
,
src/sound/typedefs/
相关技能: ../loading-assets/SKILL.md, ../game-setup-and-config/SKILL.md

Quick Start

快速入门

js
class GameScene extends Phaser.Scene {
    preload() {
        this.load.audio('bgm', 'assets/music.mp3');
        this.load.audio('coin', ['assets/coin.ogg', 'assets/coin.mp3']);
    }

    create() {
        // Fire-and-forget (auto-destroys when complete)
        this.sound.play('coin');

        // Retained reference for ongoing control
        this.music = this.sound.add('bgm', { loop: true, volume: 0.5 });
        this.music.play();
    }
}
Assets loaded via
this.load.audio()
in
preload()
are ready by the time
create()
runs. Provide an array of URLs for cross-browser format fallback.
js
class GameScene extends Phaser.Scene {
    preload() {
        this.load.audio('bgm', 'assets/music.mp3');
        this.load.audio('coin', ['assets/coin.ogg', 'assets/coin.mp3']);
    }

    create() {
        // 一次性播放(播放完成后自动销毁)
        this.sound.play('coin');

        // 保留引用以便持续控制
        this.music = this.sound.add('bgm', { loop: true, volume: 0.5 });
        this.music.play();
    }
}
preload()
中通过
this.load.audio()
加载的资源,会在
create()
执行时准备完毕。可以提供URL数组以实现跨浏览器格式兼容。

Core Concepts

核心概念

WebAudio vs HTML5 Audio

WebAudio 与 HTML5 Audio

Phaser auto-selects the best backend via
SoundManagerCreator.create()
:
  1. If
    config.audio.noAudio
    is true, or the device supports neither Web Audio nor HTML5 Audio, a NoAudioSoundManager is created (all calls are no-ops).
  2. If the device supports Web Audio and
    config.audio.disableWebAudio
    is not true, a WebAudioSoundManager is created (preferred).
  3. Otherwise, an HTML5AudioSoundManager is created as fallback.
WebAudio advantages: precise timing, gapless looping, stereo panning (
StereoPannerNode
), spatial audio (
PannerNode
), per-sound gain nodes,
decodeAudio()
for runtime decoding.
HTML5 Audio limitations: no spatial audio, no real stereo panning (pan fires events but no audible effect), less precise looping, requires
instances
count at load time for simultaneous playback.
Force HTML5 or disable audio via game config:
audio: { disableWebAudio: true }
or
audio: { noAudio: true }
. Pass
audio: { context: existingAudioContext }
to reuse a WebAudio context in SPAs.
Phaser通过
SoundManagerCreator.create()
自动选择最佳后端:
  1. 如果
    config.audio.noAudio
    为true,或设备既不支持Web Audio也不支持HTML5 Audio,则创建NoAudioSoundManager(所有调用均为空操作)。
  2. 如果设备支持Web Audio且
    config.audio.disableWebAudio
    不为true,则创建WebAudioSoundManager(优先选择)。
  3. 否则,创建HTML5AudioSoundManager作为降级方案。
WebAudio优势:精确的时序控制、无缝循环、立体声像定位(
StereoPannerNode
)、空间音频(
PannerNode
)、单音效增益节点、支持
decodeAudio()
进行运行时解码。
HTML5 Audio限制:不支持空间音频、无真实立体声像定位(触发事件但无听觉效果)、循环精度较低、加载时需指定
instances
数量以支持同时播放。
可通过游戏配置强制使用HTML5或禁用音频:
audio: { disableWebAudio: true }
audio: { noAudio: true }
。在单页应用中,可传入
audio: { context: existingAudioContext }
以复用WebAudio上下文。

The SoundManager (
this.sound
)

SoundManager(
this.sound

Accessed via
this.sound
in any Scene. It is a single shared instance across the entire game. Key responsibilities:
  • Adding, playing, and removing sound instances
  • Global volume, mute, rate, and detune
  • Automatic pause/resume when the browser tab loses/gains focus (
    pauseOnBlur
    , default
    true
    )
  • Audio unlock handling for mobile browsers
  • Spatial audio listener position (WebAudio only)
可在任意Scene中通过
this.sound
访问,它是整个游戏的单一共享实例。主要职责:
  • 添加、播放和移除音效实例
  • 全局音量、静音、播放速率和音调偏移控制
  • 浏览器标签失去/获得焦点时自动暂停/恢复(
    pauseOnBlur
    ,默认
    true
  • 移动端浏览器的音频解锁处理
  • 空间音频监听位置控制(仅WebAudio支持)

Sound Instances

音效实例

Created via
this.sound.add(key, config)
. Each instance has its own playback state, volume, rate, detune, loop, pan, and seek properties. A sound must exist in the audio cache (loaded via the Loader) before it can be added.
State flags:
isPlaying
(boolean),
isPaused
(boolean).
js
const sfx = this.sound.add('explosion', { volume: 0.8 });
sfx.play();        // returns boolean
sfx.pause();       // only works if isPlaying
sfx.resume();      // only works if isPaused
sfx.stop();        // resets to stopped state
sfx.destroy();     // marks for removal from manager
通过
this.sound.add(key, config)
创建。每个实例拥有独立的播放状态、音量、速率、音调偏移、循环、声像和进度属性。音效必须先通过Loader加载到音频缓存中,才能被添加。
状态标识:
isPlaying
(布尔值)、
isPaused
(布尔值)。
js
const sfx = this.sound.add('explosion', { volume: 0.8 });
sfx.play();        // 返回布尔值
sfx.pause();       // 仅在isPlaying状态有效
sfx.resume();      // 仅在isPaused状态有效
sfx.stop();        // 重置为停止状态
sfx.destroy();     // 标记为从管理器中移除

Common Patterns

常见模式

Playing Sounds

播放音效

Fire-and-forget --
this.sound.play(key, config?)
adds, plays, and auto-destroys the sound on completion:
js
this.sound.play('explosion');
this.sound.play('powerup', { volume: 0.5, rate: 1.2 });
Retained reference --
this.sound.add(key, config?)
then call
play()
on the instance:
js
const laser = this.sound.add('laser');
laser.play();
// Later: laser.stop(), laser.volume = 0.3, etc.
一次性播放 --
this.sound.play(key, config?)
添加、播放音效,并在播放完成后自动销毁:
js
this.sound.play('explosion');
this.sound.play('powerup', { volume: 0.5, rate: 1.2 });
保留引用 --
this.sound.add(key, config?)
然后调用实例的
play()
方法:
js
const laser = this.sound.add('laser');
laser.play();
// 后续操作:laser.stop(), laser.volume = 0.3 等

Volume, Rate, and Detune

音量、速率与音调偏移

Each property can be set per-sound or globally on the manager. Global and per-sound values combine (for rate/detune, they multiply via
calculateRate()
).
js
// Per-sound
sound.volume = 0.5;          // 0 to 1
sound.setVolume(0.5);        // chainable alternative
sound.rate = 1.5;            // 0.5 = half speed, 2.0 = double speed
sound.setRate(1.5);
sound.detune = 200;          // cents, -1200 to 1200
sound.setDetune(200);

// Global (affects all sounds)
this.sound.volume = 0.8;
this.sound.setVolume(0.8);
this.sound.rate = 1.0;
this.sound.setRate(1.0);
this.sound.detune = 0;
this.sound.setDetune(0);
The effective playback rate is:
sound.rate * manager.rate * detuneRate
where
detuneRate = Math.pow(1.0005777895065548, sound.detune + manager.detune)
.
每个属性可针对单个音效设置,也可在管理器上全局设置。全局和单个音效的值会组合生效(速率/音调偏移通过
calculateRate()
相乘)。
js
// 单个音效设置
sound.volume = 0.5;          // 取值范围0到1
sound.setVolume(0.5);        // 链式调用的替代方式
sound.rate = 1.5;            // 0.5为半速,2.0为双倍速
sound.setRate(1.5);
sound.detune = 200;          // 音分,取值范围-1200到1200
sound.setDetune(200);

// 全局设置(影响所有音效)
this.sound.volume = 0.8;
this.sound.setVolume(0.8);
this.sound.rate = 1.0;
this.sound.setRate(1.0);
this.sound.detune = 0;
this.sound.setDetune(0);
实际播放速率为:
sound.rate * manager.rate * detuneRate
,其中
detuneRate = Math.pow(1.0005777895065548, sound.detune + manager.detune)

Looping

循环播放

js
// Via config at creation
const bgm = this.sound.add('music', { loop: true });
bgm.play();

// Toggle during playback
bgm.loop = false;
bgm.setLoop(false);  // chainable
The
LOOPED
event fires each time the sound loops back to the start. The
LOOP
event fires when the loop property changes.
js
// 创建时通过配置设置
const bgm = this.sound.add('music', { loop: true });
bgm.play();

// 播放过程中切换
 bgm.loop = false;
 bgm.setLoop(false);  // 链式调用
每次音效循环回到开头时会触发
LOOPED
事件。当循环属性改变时会触发
LOOP
事件。

Seeking

进度跳转

js
sound.seek = 5.0;        // jump to 5 seconds in
sound.setSeek(5.0);      // chainable
console.log(sound.seek);  // current playback position in seconds
Setting seek on a stopped sound has no effect.
js
sound.seek = 5.0;        // 跳转到第5秒
sound.setSeek(5.0);      // 链式调用
console.log(sound.seek);  // 当前播放位置(秒)
对已停止的音效设置进度无效。

Stereo Panning

立体声像定位

js
sound.pan = -1;   // full left
sound.pan = 0;    // center
sound.pan = 1;    // full right
sound.setPan(0.5); // chainable
Uses
StereoPannerNode
, if it exists, on WebAudio. On HTML5 Audio, the pan property fires events but has no audible effect.
js
sound.pan = -1;   // 完全左声道
sound.pan = 0;    // 居中
sound.pan = 1;    // 完全右声道
sound.setPan(0.5); // 链式调用
在WebAudio中使用
StereoPannerNode
(如果存在)。在HTML5 Audio中,声像属性会触发事件但无听觉效果。

Audio Sprites and Markers

音频精灵与标记点

Audio sprites combine multiple sounds into a single audio file with a JSON config (generated by the
audiosprite
tool). The JSON must be loaded separately.
js
// In preload
this.load.audioSprite('sfx', 'assets/sfx.json', ['assets/sfx.ogg', 'assets/sfx.mp3']);

// In create
this.sound.playAudioSprite('sfx', 'explosion');
this.sound.playAudioSprite('sfx', 'coin', { volume: 0.5 });

// Or add for retained control
const sprite = this.sound.addAudioSprite('sfx');
sprite.play('explosion');
The JSON
spritemap
entries are automatically converted to markers with
name
,
start
,
duration
, and optional
loop
.
Manual markers -- you can also add markers to any sound:
js
const sound = this.sound.add('longtrack');

sound.addMarker({ name: 'intro', start: 0, duration: 5 });
sound.addMarker({ name: 'loop', start: 5, duration: 20, config: { loop: true } });
sound.addMarker({ name: 'outro', start: 25, duration: 3 });

sound.play('intro');
// Later
sound.play('loop');
Marker API on BaseSound:
addMarker(marker)
,
updateMarker(marker)
,
removeMarker(markerName)
.
音频精灵将多个音效合并到单个音频文件中,并配合JSON配置(由
audiosprite
工具生成)。JSON文件需单独加载。
js
// 在preload中
this.load.audioSprite('sfx', 'assets/sfx.json', ['assets/sfx.ogg', 'assets/sfx.mp3']);

// 在create中
this.sound.playAudioSprite('sfx', 'explosion');
this.sound.playAudioSprite('sfx', 'coin', { volume: 0.5 });

// 或添加以保留控制权限
const sprite = this.sound.addAudioSprite('sfx');
sprite.play('explosion');
JSON中的
spritemap
条目会自动转换为包含
name
start
duration
和可选
loop
的标记点。
手动添加标记点 -- 你也可以为任意音效添加标记点:
js
const sound = this.sound.add('longtrack');

sound.addMarker({ name: 'intro', start: 0, duration: 5 });
sound.addMarker({ name: 'loop', start: 5, duration: 20, config: { loop: true } });
sound.addMarker({ name: 'outro', start: 25, duration: 3 });

sound.play('intro');
// 后续操作
sound.play('loop');
BaseSound上的标记点API:
addMarker(marker)
updateMarker(marker)
removeMarker(markerName)

Background Music Pattern

背景音乐模式

js
this.bgm = this.sound.add('theme', { loop: true, volume: 0.4 });
this.bgm.play();
// Stop on scene shutdown: this.bgm.stop();
The manager's
pauseOnBlur
(default
true
) automatically pauses all sounds when the tab loses focus.
js
this.bgm = this.sound.add('theme', { loop: true, volume: 0.4 });
this.bgm.play();
// 场景关闭时停止:this.bgm.stop();
管理器的
pauseOnBlur
(默认
true
)会在标签失去焦点时自动暂停所有音效。

Spatial Audio (WebAudio Only)

空间音频(仅WebAudio支持)

Spatial audio uses the Web Audio
PannerNode
to position sounds in 2D/3D space relative to a listener.
js
// Set the listener position (typically your camera or player)
this.sound.setListenerPosition(400, 300);
// Or update directly: this.sound.listenerPosition.set(x, y);

// Create a spatialized sound with a source config
const enemy = this.sound.add('roar', {
    source: {
        x: 800,
        y: 300,
        refDistance: 50,
        maxDistance: 2000,
        rolloffFactor: 1,
        distanceModel: 'inverse',
        panningModel: 'equalpower',
        follow: enemySprite  // auto-track a Game Object's x/y
    }
});
enemy.play();
You can set
sound.x
and
sound.y
directly on a WebAudioSound to reposition it at any time. If
follow
is set to an object with
x
/
y
properties, the spatial position updates automatically each frame.
setListenerPosition()
defaults to the center of the game canvas if called with no arguments.
空间音频使用Web Audio的
PannerNode
将音效定位在2D/3D空间中,相对于监听者位置。
js
// 设置监听者位置(通常为相机或玩家位置)
this.sound.setListenerPosition(400, 300);
// 或直接更新:this.sound.listenerPosition.set(x, y);

// 创建带源配置的空间化音效
const enemy = this.sound.add('roar', {
    source: {
        x: 800,
        y: 300,
        refDistance: 50,
        maxDistance: 2000,
        rolloffFactor: 1,
        distanceModel: 'inverse',
        panningModel: 'equalpower',
        follow: enemySprite  // 自动跟踪游戏对象的x/y位置
    }
});
enemy.play();
你可以直接设置WebAudioSound的
sound.x
sound.y
随时重新定位音效。如果
follow
设置为带有
x
/
y
属性的对象,空间位置会在每一帧自动更新。
如果调用
setListenerPosition()
时不传入参数,默认会设置为游戏画布的中心。

Muting

静音控制

js
// Per-sound
sound.mute = true;
sound.setMute(true);

// Global
this.sound.mute = true;
this.sound.setMute(true);
js
// 单个音效静音
sound.mute = true;
sound.setMute(true);

// 全局静音
this.sound.mute = true;
this.sound.setMute(true);

Querying Sounds

查询音效

js
this.sound.get('coin');          // first sound with key, or null
this.sound.getAll('coin');       // all sounds with key
this.sound.getAll();             // every sound in the manager
this.sound.getAllPlaying();      // all currently playing sounds
this.sound.isPlaying('coin');    // true if any 'coin' sound is playing
this.sound.isPlaying();          // true if any sound is playing
js
this.sound.get('coin');          // 获取第一个key为'coin'的音效,不存在则返回null
this.sound.getAll('coin');       // 获取所有key为'coin'的音效
this.sound.getAll();             // 获取管理器中的所有音效
this.sound.getAllPlaying();      // 获取所有正在播放的音效
this.sound.isPlaying('coin');    // 如果有任意'coin'音效正在播放则返回true
this.sound.isPlaying();          // 如果有任意音效正在播放则返回true

Removing and Stopping

移除与停止音效

js
this.sound.stopAll();            // stop all sounds, fires STOP_ALL
this.sound.stopByKey('coin');    // stop all sounds with key, returns count
this.sound.pauseAll();           // pause all, fires PAUSE_ALL
this.sound.resumeAll();          // resume all, fires RESUME_ALL

this.sound.remove(soundInstance);  // destroy + remove specific sound
this.sound.removeByKey('coin');    // destroy + remove all with key, returns count
this.sound.removeAll();            // destroy + remove everything
js
this.sound.stopAll();            // 停止所有音效,触发STOP_ALL事件
this.sound.stopByKey('coin');    // 停止所有key为'coin'的音效,返回数量
this.sound.pauseAll();           // 暂停所有音效,触发PAUSE_ALL事件
this.sound.resumeAll();          // 恢复所有音效,触发RESUME_ALL事件

this.sound.remove(soundInstance);  // 销毁并移除指定音效
this.sound.removeByKey('coin');    // 销毁并移除所有key为'coin'的音效,返回数量
this.sound.removeAll();            // 销毁并移除所有音效

Decoding Audio at Runtime (WebAudio Only)

运行时解码音频(仅WebAudio支持)

js
this.sound.decodeAudio('key', base64StringOrArrayBuffer);
// Or batch: this.sound.decodeAudio([{ key: 'sfx1', data: buf1 }, { key: 'sfx2', data: buf2 }]);
this.sound.on('decoded', (key) => { /* one done */ });
this.sound.on('decodedall', () => { /* all done */ });
js
this.sound.decodeAudio('key', base64StringOrArrayBuffer);
// 或批量解码:this.sound.decodeAudio([{ key: 'sfx1', data: buf1 }, { key: 'sfx2', data: buf2 }]);
this.sound.on('decoded', (key) => { /* 单个音频解码完成 */ });
this.sound.on('decodedall', () => { /* 所有排队音频解码完成 */ });

Configuration Reference

配置参考

SoundConfig

SoundConfig

PropertyTypeDefaultDescription
mute
boolean
false
Whether the sound is muted
volume
number
1
Volume, 0 (silence) to 1 (full)
rate
number
1
Playback speed (0.5 = half, 2.0 = double)
detune
number
0
Detuning in cents (-1200 to 1200)
seek
number
0
Start playback position in seconds
loop
boolean
false
Whether the sound should loop
delay
number
0
Delay before playback starts, in seconds
pan
number
0
Stereo pan, -1 (left) to 1 (right)
source
SpatialSoundConfig
null
Spatial audio configuration (WebAudio only)
属性类型默认值描述
mute
boolean
false
音效是否静音
volume
number
1
音量,取值0(静音)到1(最大)
rate
number
1
播放速率(0.5为半速,2.0为双倍速)
detune
number
0
音调偏移(音分),取值-1200到1200
seek
number
0
播放起始位置(秒)
loop
boolean
false
音效是否循环播放
delay
number
0
播放延迟时间(秒)
pan
number
0
立体声像,取值-1(左)到1(右)
source
SpatialSoundConfig
null
空间音频配置(仅WebAudio支持)

SpatialSoundConfig

SpatialSoundConfig

Position:
x
(0),
y
(0),
z
(0) -- source position in world space. Orientation:
orientationX
(0),
orientationY
(0),
orientationZ
(-1) -- source direction vector. Models:
panningModel
(
'equalpower'
or
'HRTF'
),
distanceModel
(
'linear'
,
'inverse'
,
'exponential'
). Distance:
refDistance
(1),
maxDistance
(10000),
rolloffFactor
(1). Cone:
coneInnerAngle
(360),
coneOuterAngle
(0),
coneOuterGain
(0). Tracking:
follow
(null) -- a Vector2Like object whose x/y is auto-tracked each frame.
位置:
x
(0)、
y
(0)、
z
(0)-- 音效源在世界空间中的位置。 方向:
orientationX
(0)、
orientationY
(0)、
orientationZ
(-1)-- 音效源的方向向量。 模型:
panningModel
'equalpower'
'HRTF'
)、
distanceModel
'linear'
'inverse'
'exponential'
)。 距离:
refDistance
(1)、
maxDistance
(10000)、
rolloffFactor
(1)。 锥形区域:
coneInnerAngle
(360)、
coneOuterAngle
(0)、
coneOuterGain
(0)。 跟踪:
follow
(null)-- 带有x/y属性的Vector2Like对象,其位置会在每一帧自动跟踪。

SoundMarker

SoundMarker

PropertyTypeDefaultDescription
name
string(required)Unique identifier for the marker
start
number
0
Start position in seconds
duration
number(remaining)Playback duration in seconds
config
SoundConfig
{}
Default settings for this marker
属性类型默认值描述
name
string必填标记点的唯一标识符
start
number
0
起始位置(秒)
duration
number剩余时长播放时长(秒)
config
SoundConfig
{}
此标记点的默认设置

Events

事件

Sound Instance Events (emitted on a Sound object)

音效实例事件(在Sound对象上触发)

Event ConstantString ValueCallback ArgsWhen
Events.PLAY
'play'
(sound)
Sound starts playing
Events.PAUSE
'pause'
(sound)
Sound is paused
Events.RESUME
'resume'
(sound)
Sound resumes from pause
Events.STOP
'stop'
(sound)
Sound is stopped
Events.COMPLETE
'complete'
(sound)
Sound finishes (non-looping)
Events.LOOPED
'looped'
(sound)
Sound loops back to start
Events.LOOP
'loop'
(sound, value)
Loop property changes
Events.MUTE
'mute'
(sound, value)
Mute state changes
Events.VOLUME
'volume'
(sound, value)
Volume changes
Events.RATE
'rate'
(sound, value)
Rate changes
Events.DETUNE
'detune'
(sound, value)
Detune changes
Events.SEEK
'seek'
(sound, value)
Seek position changes
Events.PAN
'pan'
(sound, value)
Pan value changes
Events.DESTROY
'destroy'
(sound)
Sound is destroyed
事件常量字符串值回调参数触发时机
Events.PLAY
'play'
(sound)
音效开始播放时
Events.PAUSE
'pause'
(sound)
音效暂停时
Events.RESUME
'resume'
(sound)
音效从暂停恢复时
Events.STOP
'stop'
(sound)
音效停止时
Events.COMPLETE
'complete'
(sound)
音效播放完成(非循环)时
Events.LOOPED
'looped'
(sound)
音效循环回到开头时
Events.LOOP
'loop'
(sound, value)
循环属性改变时
Events.MUTE
'mute'
(sound, value)
静音状态改变时
Events.VOLUME
'volume'
(sound, value)
音量改变时
Events.RATE
'rate'
(sound, value)
播放速率改变时
Events.DETUNE
'detune'
(sound, value)
音调偏移改变时
Events.SEEK
'seek'
(sound, value)
进度位置改变时
Events.PAN
'pan'
(sound, value)
声像值改变时
Events.DESTROY
'destroy'
(sound)
音效被销毁时

SoundManager Events (emitted on
this.sound
)

SoundManager事件(在
this.sound
上触发)

Event ConstantString ValueCallback ArgsWhen
Events.PAUSE_ALL
'pauseall'
(manager)
pauseAll()
called
Events.RESUME_ALL
'resumeall'
(manager)
resumeAll()
called
Events.STOP_ALL
'stopall'
(manager)
stopAll()
called
Events.GLOBAL_MUTE
'globalmute'
(manager, value)
Global mute changes
Events.GLOBAL_VOLUME
'globalvolume'
(manager, value)
Global volume changes
Events.GLOBAL_RATE
'globalrate'
(manager, value)
Global rate changes
Events.GLOBAL_DETUNE
'globaldetune'
(manager, value)
Global detune changes
Events.UNLOCKED
'unlocked'
(manager)
Audio system unlocked after user interaction
Events.DECODED
'decoded'
(key)
Single audio key decoded (WebAudio)
Events.DECODED_ALL
'decodedall'
()
All queued audio decoded (WebAudio)
js
// Example: listen for completion
const sfx = this.sound.add('bang');
sfx.on('complete', (sound) => {
    console.log(sound.key, 'finished');
});
sfx.play();
事件常量字符串值回调参数触发时机
Events.PAUSE_ALL
'pauseall'
(manager)
调用
pauseAll()
Events.RESUME_ALL
'resumeall'
(manager)
调用
resumeAll()
Events.STOP_ALL
'stopall'
(manager)
调用
stopAll()
Events.GLOBAL_MUTE
'globalmute'
(manager, value)
全局静音状态改变时
Events.GLOBAL_VOLUME
'globalvolume'
(manager, value)
全局音量改变时
Events.GLOBAL_RATE
'globalrate'
(manager, value)
全局播放速率改变时
Events.GLOBAL_DETUNE
'globaldetune'
(manager, value)
全局音调偏移改变时
Events.UNLOCKED
'unlocked'
(manager)
用户交互后音频系统解锁时
Events.DECODED
'decoded'
(key)
单个音频key解码完成(WebAudio)时
Events.DECODED_ALL
'decodedall'
()
所有排队音频解码完成(WebAudio)时
js
// 示例:监听播放完成事件
const sfx = this.sound.add('bang');
sfx.on('complete', (sound) => {
    console.log(sound.key, '播放完成');
});
sfx.play();

API Quick Reference

API快速参考

BaseSoundManager (
this.sound
)

BaseSoundManager(
this.sound

Methods:
add(key, config?)
,
addAudioSprite(key, config?)
,
play(key, extra?)
,
playAudioSprite(key, spriteName, config?)
,
get(key)
,
getAll(key?)
,
getAllPlaying()
,
isPlaying(key?)
,
remove(sound)
,
removeByKey(key)
,
removeAll()
,
stopAll()
,
stopByKey(key)
,
pauseAll()
,
resumeAll()
,
setListenerPosition(x?, y?)
,
setMute(value)
,
setVolume(value)
,
setRate(value)
,
setDetune(value)
.
Properties:
volume
(0-1),
mute
(boolean),
rate
(number),
detune
(-1200 to 1200),
pauseOnBlur
(boolean, default true),
locked
(boolean, read-only),
listenerPosition
(Vector2),
sounds
(array, private).
方法:
add(key, config?)
,
addAudioSprite(key, config?)
,
play(key, extra?)
,
playAudioSprite(key, spriteName, config?)
,
get(key)
,
getAll(key?)
,
getAllPlaying()
,
isPlaying(key?)
,
remove(sound)
,
removeByKey(key)
,
removeAll()
,
stopAll()
,
stopByKey(key)
,
pauseAll()
,
resumeAll()
,
setListenerPosition(x?, y?)
,
setMute(value)
,
setVolume(value)
,
setRate(value)
,
setDetune(value)
.
属性:
volume
(0-1)、
mute
(布尔值)、
rate
(数值)、
detune
(-1200到1200)、
pauseOnBlur
(布尔值,默认true)、
locked
(布尔值,只读)、
listenerPosition
(Vector2)、
sounds
(数组,私有)。

BaseSound (sound instance)

BaseSound(音效实例)

Methods:
play(markerName?, config?)
,
pause()
,
resume()
,
stop()
,
destroy()
,
addMarker(marker)
,
updateMarker(marker)
,
removeMarker(name)
,
setMute(value)
,
setVolume(value)
,
setRate(value)
,
setDetune(value)
,
setSeek(value)
,
setLoop(value)
,
setPan(value)
.
Properties:
volume
(0-1),
mute
(boolean),
rate
(number),
detune
(number),
seek
(seconds),
loop
(boolean),
pan
(-1 to 1),
isPlaying
(read-only),
isPaused
(read-only),
duration
(seconds),
totalDuration
(seconds),
key
(string),
x
/
y
(spatial position, WebAudio only).
All
set*
methods return
this
for chaining.
方法:
play(markerName?, config?)
,
pause()
,
resume()
,
stop()
,
destroy()
,
addMarker(marker)
,
updateMarker(marker)
,
removeMarker(name)
,
setMute(value)
,
setVolume(value)
,
setRate(value)
,
setDetune(value)
,
setSeek(value)
,
setLoop(value)
,
setPan(value)
.
属性:
volume
(0-1)、
mute
(布尔值)、
rate
(数值)、
detune
(数值)、
seek
(秒)、
loop
(布尔值)、
pan
(-1到1)、
isPlaying
(只读)、
isPaused
(只读)、
duration
(秒)、
totalDuration
(秒)、
key
(字符串)、
x
/
y
(空间位置,仅WebAudio支持)。
所有
set*
方法返回
this
以支持链式调用。

Gotchas

注意事项

Browser Autoplay Policy

浏览器自动播放策略

Browsers block audio until user interaction. Phaser handles this automatically:
  • WebAudio:
    AudioContext
    starts suspended. Phaser listens for touchstart/touchend/mousedown/mouseup/keydown on
    document.body
    to call
    context.resume()
    . The
    locked
    property is true until unlocked;
    UNLOCKED
    event fires once resolved.
  • HTML5 Audio: Locked audio tags queue all actions until the first touch replays them.
You do not need to handle unlocking manually. To know when ready, listen for
UNLOCKED
:
js
if (this.sound.locked) {
    this.sound.once('unlocked', () => {
        this.sound.play('bgm');
    });
} else {
    this.sound.play('bgm');
}
浏览器会阻止音频自动播放,直到用户进行交互。Phaser会自动处理此问题:
  • WebAudio
    AudioContext
    初始为暂停状态。Phaser会监听
    document.body
    上的touchstart/touchend/mousedown/mouseup/keydown事件,调用
    context.resume()
    locked
    属性在解锁前为true;解锁后会触发
    UNLOCKED
    事件。
  • HTML5 Audio:锁定的音频标签会将所有操作加入队列,直到第一次触摸操作后重新执行。
无需手动处理解锁。如需知道何时准备就绪,可监听
UNLOCKED
事件:
js
if (this.sound.locked) {
    this.sound.once('unlocked', () => {
        this.sound.play('bgm');
    });
} else {
    this.sound.play('bgm');
}

Audio Format Support

音频格式支持

No single format works everywhere. Provide multiple formats:
this.load.audio('bgm', ['assets/bgm.ogg', 'assets/bgm.mp3'])
. MP3 has broadest support. OGG Vorbis lacks Safari support. AAC/M4A works well on Safari/iOS. WebM/Opus has excellent quality but limited older browser support.
没有单一格式能在所有环境中生效。提供多种格式:
this.load.audio('bgm', ['assets/bgm.ogg', 'assets/bgm.mp3'])
。MP3支持最广泛。OGG Vorbis不支持Safari。AAC/M4A在Safari/iOS上表现良好。WebM/Opus音质极佳但对旧浏览器支持有限。

HTML5 Audio Simultaneous Playback

HTML5 Audio同时播放

HTML5 Audio uses a pool of
<audio>
tags. Specify
instances
when loading for simultaneous playback:
this.load.audio('shot', 'assets/shot.mp3', { instances: 4 })
. Default is 1. If all tags are in use and
manager.override
is true (default), the sound with the most progress is hijacked. WebAudio has no such limitation.
HTML5 Audio使用
<audio>
标签池。加载时需指定
instances
数量以支持同时播放:
this.load.audio('shot', 'assets/shot.mp3', { instances: 4 })
。默认值为1。如果所有标签都在使用中且
manager.override
为true(默认),则会抢占进度最靠前的音效。WebAudio无此限制。

iOS/Safari Specifics

iOS/Safari特定问题

  • StereoPannerNode
    not supported on iOS/Safari, so
    pan
    has no audible effect (events still fire).
  • iOS 17/18+ can interrupt audio on background. Phaser handles this via
    context.suspend()
    /
    context.resume()
    on the
    VISIBLE
    game event.
  • setListenerPosition()
    and spatial audio are WebAudio-only.
  • iOS/Safari不支持
    StereoPannerNode
    ,因此
    pan
    无听觉效果(事件仍会触发)。
  • iOS 17/18+会在后台中断音频。Phaser通过
    VISIBLE
    游戏事件调用
    context.suspend()
    /
    context.resume()
    处理此问题。
  • setListenerPosition()
    和空间音频仅支持WebAudio。

WebAudio Context Reuse

WebAudio上下文复用

For SPAs that recreate the game without a full page reload, pass
audio: { context: existingAudioContext }
in the game config. You can also swap contexts at runtime via
this.sound.setAudioContext(newContext)
(WebAudio only).
对于不刷新页面就重新创建游戏的单页应用,可在游戏配置中传入
audio: { context: existingAudioContext }
。也可在运行时通过
this.sound.setAudioContext(newContext)
切换上下文(仅WebAudio支持)。

Sound Manager is Shared (Global)

SoundManager是全局共享的

There is one SoundManager per game, not per scene.
this.sound
in every scene references the same manager. Sounds are not automatically cleaned up on scene shutdown -- you must stop/remove them yourself if needed. Looping sounds will continue playing across scene changes unless explicitly stopped.
每个游戏仅有一个SoundManager,而非每个场景一个。所有场景中的
this.sound
都指向同一个管理器。场景关闭时音效不会自动清理 -- 如需清理必须手动停止/移除。循环播放的音效会在场景切换后继续播放,除非显式停止。

Fire-and-Forget vs Persistent Sounds

一次性播放 vs 持久音效

this.sound.play(key)
creates a sound that auto-destroys on completion -- you cannot control it after calling play. Use
this.sound.add(key)
when you need a persistent reference to pause, stop, adjust volume, or listen for events.
this.sound.play(key)
创建的音效会在播放完成后自动销毁 -- 调用play后无法再控制它。当你需要持久引用以暂停、停止、调整音量或监听事件时,使用
this.sound.add(key)

Spatial Audio is WebAudio Only

空间音频仅支持WebAudio

The
source
config for spatial audio is silently ignored when using HTML5 Audio. If your game must support HTML5 Audio fallback, do not rely on spatial positioning for gameplay-critical audio cues.
空间音频的
source
配置在使用HTML5 Audio时会被静默忽略。如果你的游戏必须支持HTML5 Audio降级方案,请勿依赖空间定位作为游戏关键音频提示。

Web Audio Analyser (WebAudio Only)

Web Audio分析器(仅WebAudio支持)

Access the underlying
AudioContext
to create an
AnalyserNode
for frequency/waveform visualization:
js
const analyser = this.sound.context.createAnalyser();
analyser.fftSize = 256;
this.sound.masterVolumeNode.connect(analyser);
analyser.connect(this.sound.context.destination);

const dataArray = new Uint8Array(analyser.frequencyBinCount);

// In update loop
analyser.getByteFrequencyData(dataArray);
// Use dataArray values to drive visual effects
This only works with the WebAudioSoundManager. Check
this.sound.context
exists before using.
访问底层
AudioContext
创建
AnalyserNode
以实现频率/波形可视化:
js
const analyser = this.sound.context.createAnalyser();
analyser.fftSize = 256;
this.sound.masterVolumeNode.connect(analyser);
analyser.connect(this.sound.context.destination);

const dataArray = new Uint8Array(analyser.frequencyBinCount);

// 在更新循环中
analyser.getByteFrequencyData(dataArray);
// 使用dataArray的值驱动视觉效果
此功能仅适用于WebAudioSoundManager。使用前需检查
this.sound.context
是否存在。

Source File Map

源码文件映射

FilePurpose
src/sound/SoundManagerCreator.js
Factory: picks WebAudio, HTML5, or NoAudio manager
src/sound/BaseSoundManager.js
Base manager: add, play, get, stop/pause/resume all, global volume/rate/detune
src/sound/BaseSound.js
Base sound: play/pause/resume/stop, markers, config, calculateRate
src/sound/webaudio/WebAudioSoundManager.js
WebAudio manager: AudioContext, gain nodes, unlock, spatial listener, decodeAudio
src/sound/webaudio/WebAudioSound.js
WebAudio sound: buffer sources, spatial/panner nodes, seek, all properties
src/sound/html5/HTML5AudioSoundManager.js
HTML5 manager: audio tag pooling, locked queue, override
src/sound/html5/HTML5AudioSound.js
HTML5 sound: tag-based playback, limited feature set
src/sound/noaudio/NoAudioSoundManager.js
No-op manager for environments without audio
src/sound/events/
All sound event constants (PLAY, STOP, COMPLETE, etc.)
src/sound/typedefs/SoundConfig.js
SoundConfig type definition
src/sound/typedefs/SoundMarker.js
SoundMarker type definition
src/sound/typedefs/SpatialSoundConfig.js
SpatialSoundConfig type definition
src/sound/typedefs/AudioSpriteSound.js
AudioSpriteSound type definition
文件用途
src/sound/SoundManagerCreator.js
工厂类:选择WebAudio、HTML5或NoAudio管理器
src/sound/BaseSoundManager.js
基础管理器:添加、播放、获取、批量停止/暂停/恢复、全局音量/速率/音调偏移控制
src/sound/BaseSound.js
基础音效类:播放/暂停/恢复/停止、标记点、配置、速率计算
src/sound/webaudio/WebAudioSoundManager.js
WebAudio管理器:AudioContext、增益节点、解锁、空间监听、音频解码
src/sound/webaudio/WebAudioSound.js
WebAudio音效类:缓冲源、空间/声像节点、进度跳转、所有属性控制
src/sound/html5/HTML5AudioSoundManager.js
HTML5管理器:音频标签池、锁定队列、抢占机制
src/sound/html5/HTML5AudioSound.js
HTML5音效类:基于标签的播放、有限功能集
src/sound/noaudio/NoAudioSoundManager.js
无音频环境的空操作管理器
src/sound/events/
所有音效事件常量(PLAY、STOP、COMPLETE等)
src/sound/typedefs/SoundConfig.js
SoundConfig类型定义
src/sound/typedefs/SoundMarker.js
SoundMarker类型定义
src/sound/typedefs/SpatialSoundConfig.js
SpatialSoundConfig类型定义
src/sound/typedefs/AudioSpriteSound.js
AudioSpriteSound类型定义