audio-and-sound
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAudio and Sound
音频与音效
Phaser provides a unified Sound system via(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.this.sound
Key source paths: , , , , , ,
Related skills: ../loading-assets/SKILL.md, ../game-setup-and-config/SKILL.md
src/sound/BaseSoundManager.jssrc/sound/BaseSound.jssrc/sound/webaudio/src/sound/html5/src/sound/SoundManagerCreator.jssrc/sound/events/src/sound/typedefs/Phaser通过(一个SoundManager)提供统一的音效系统,它对Web Audio API和HTML5 Audio进行了抽象封装。该系统负责处理音频加载、播放、音量控制、声像定位、循环播放、标记点、音频精灵、空间音频以及浏览器自动播放策略解锁等功能。this.sound
核心源码路径: , , , , , ,
相关技能: ../loading-assets/SKILL.md, ../game-setup-and-config/SKILL.md
src/sound/BaseSoundManager.jssrc/sound/BaseSound.jssrc/sound/webaudio/src/sound/html5/src/sound/SoundManagerCreator.jssrc/sound/events/src/sound/typedefs/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 in are ready by the time runs. Provide an array of URLs for cross-browser format fallback.
this.load.audio()preload()create()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();
}
}在中通过加载的资源,会在执行时准备完毕。可以提供URL数组以实现跨浏览器格式兼容。
preload()this.load.audio()create()Core Concepts
核心概念
WebAudio vs HTML5 Audio
WebAudio 与 HTML5 Audio
Phaser auto-selects the best backend via :
SoundManagerCreator.create()- If is true, or the device supports neither Web Audio nor HTML5 Audio, a NoAudioSoundManager is created (all calls are no-ops).
config.audio.noAudio - If the device supports Web Audio and is not true, a WebAudioSoundManager is created (preferred).
config.audio.disableWebAudio - Otherwise, an HTML5AudioSoundManager is created as fallback.
WebAudio advantages: precise timing, gapless looping, stereo panning (), spatial audio (), per-sound gain nodes, for runtime decoding.
StereoPannerNodePannerNodedecodeAudio()HTML5 Audio limitations: no spatial audio, no real stereo panning (pan fires events but no audible effect), less precise looping, requires count at load time for simultaneous playback.
instancesForce HTML5 or disable audio via game config: or . Pass to reuse a WebAudio context in SPAs.
audio: { disableWebAudio: true }audio: { noAudio: true }audio: { context: existingAudioContext }Phaser通过自动选择最佳后端:
SoundManagerCreator.create()- 如果为true,或设备既不支持Web Audio也不支持HTML5 Audio,则创建NoAudioSoundManager(所有调用均为空操作)。
config.audio.noAudio - 如果设备支持Web Audio且不为true,则创建WebAudioSoundManager(优先选择)。
config.audio.disableWebAudio - 否则,创建HTML5AudioSoundManager作为降级方案。
WebAudio优势:精确的时序控制、无缝循环、立体声像定位()、空间音频()、单音效增益节点、支持进行运行时解码。
StereoPannerNodePannerNodedecodeAudio()HTML5 Audio限制:不支持空间音频、无真实立体声像定位(触发事件但无听觉效果)、循环精度较低、加载时需指定数量以支持同时播放。
instances可通过游戏配置强制使用HTML5或禁用音频: 或 。在单页应用中,可传入以复用WebAudio上下文。
audio: { disableWebAudio: true }audio: { noAudio: true }audio: { context: existingAudioContext }The SoundManager (this.sound
)
this.soundSoundManager(this.sound
)
this.soundAccessed via in any Scene. It is a single shared instance across the entire game. Key responsibilities:
this.sound- Adding, playing, and removing sound instances
- Global volume, mute, rate, and detune
- Automatic pause/resume when the browser tab loses/gains focus (, default
pauseOnBlur)true - Audio unlock handling for mobile browsers
- Spatial audio listener position (WebAudio only)
可在任意Scene中通过访问,它是整个游戏的单一共享实例。主要职责:
this.sound- 添加、播放和移除音效实例
- 全局音量、静音、播放速率和音调偏移控制
- 浏览器标签失去/获得焦点时自动暂停/恢复(,默认
pauseOnBlur)true - 移动端浏览器的音频解锁处理
- 空间音频监听位置控制(仅WebAudio支持)
Sound Instances
音效实例
Created via . 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.
this.sound.add(key, config)State flags: (boolean), (boolean).
isPlayingisPausedjs
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通过创建。每个实例拥有独立的播放状态、音量、速率、音调偏移、循环、声像和进度属性。音效必须先通过Loader加载到音频缓存中,才能被添加。
this.sound.add(key, config)状态标识:(布尔值)、(布尔值)。
isPlayingisPausedjs
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 -- adds, plays, and auto-destroys the sound on completion:
this.sound.play(key, config?)js
this.sound.play('explosion');
this.sound.play('powerup', { volume: 0.5, rate: 1.2 });Retained reference -- then call on the instance:
this.sound.add(key, config?)play()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: where .
sound.rate * manager.rate * detuneRatedetuneRate = 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 * detuneRatedetuneRate = 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); // chainableThe event fires each time the sound loops back to the start. The event fires when the loop property changes.
LOOPEDLOOPjs
// 创建时通过配置设置
const bgm = this.sound.add('music', { loop: true });
bgm.play();
// 播放过程中切换
bgm.loop = false;
bgm.setLoop(false); // 链式调用每次音效循环回到开头时会触发事件。当循环属性改变时会触发事件。
LOOPEDLOOPSeeking
进度跳转
js
sound.seek = 5.0; // jump to 5 seconds in
sound.setSeek(5.0); // chainable
console.log(sound.seek); // current playback position in secondsSetting 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); // chainableUses , if it exists, on WebAudio. On HTML5 Audio, the pan property fires events but has no audible effect.
StereoPannerNodejs
sound.pan = -1; // 完全左声道
sound.pan = 0; // 居中
sound.pan = 1; // 完全右声道
sound.setPan(0.5); // 链式调用在WebAudio中使用(如果存在)。在HTML5 Audio中,声像属性会触发事件但无听觉效果。
StereoPannerNodeAudio Sprites and Markers
音频精灵与标记点
Audio sprites combine multiple sounds into a single audio file with a JSON config (generated by the tool). The JSON must be loaded separately.
audiospritejs
// 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 entries are automatically converted to markers with , , , and optional .
spritemapnamestartdurationloopManual 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配置(由工具生成)。JSON文件需单独加载。
audiospritejs
// 在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中的条目会自动转换为包含、、和可选的标记点。
spritemapnamestartdurationloop手动添加标记点 -- 你也可以为任意音效添加标记点:
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 (default ) automatically pauses all sounds when the tab loses focus.
pauseOnBlurtruejs
this.bgm = this.sound.add('theme', { loop: true, volume: 0.4 });
this.bgm.play();
// 场景关闭时停止:this.bgm.stop();管理器的(默认)会在标签失去焦点时自动暂停所有音效。
pauseOnBlurtrueSpatial Audio (WebAudio Only)
空间音频(仅WebAudio支持)
Spatial audio uses the Web Audio to position sounds in 2D/3D space relative to a listener.
PannerNodejs
// 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 and directly on a WebAudioSound to reposition it at any time. If is set to an object with / properties, the spatial position updates automatically each frame.
sound.xsound.yfollowxysetListenerPosition()空间音频使用Web Audio的将音效定位在2D/3D空间中,相对于监听者位置。
PannerNodejs
// 设置监听者位置(通常为相机或玩家位置)
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.xsound.yfollowxy如果调用时不传入参数,默认会设置为游戏画布的中心。
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 playingjs
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(); // 如果有任意音效正在播放则返回trueRemoving 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 everythingjs
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
| Property | Type | Default | Description |
|---|---|---|---|
| boolean | | Whether the sound is muted |
| number | | Volume, 0 (silence) to 1 (full) |
| number | | Playback speed (0.5 = half, 2.0 = double) |
| number | | Detuning in cents (-1200 to 1200) |
| number | | Start playback position in seconds |
| boolean | | Whether the sound should loop |
| number | | Delay before playback starts, in seconds |
| number | | Stereo pan, -1 (left) to 1 (right) |
| SpatialSoundConfig | | Spatial audio configuration (WebAudio only) |
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| boolean | | 音效是否静音 |
| number | | 音量,取值0(静音)到1(最大) |
| number | | 播放速率(0.5为半速,2.0为双倍速) |
| number | | 音调偏移(音分),取值-1200到1200 |
| number | | 播放起始位置(秒) |
| boolean | | 音效是否循环播放 |
| number | | 播放延迟时间(秒) |
| number | | 立体声像,取值-1(左)到1(右) |
| SpatialSoundConfig | | 空间音频配置(仅WebAudio支持) |
SpatialSoundConfig
SpatialSoundConfig
Position: (0), (0), (0) -- source position in world space.
Orientation: (0), (0), (-1) -- source direction vector.
Models: ( or ), (, , ).
Distance: (1), (10000), (1).
Cone: (360), (0), (0).
Tracking: (null) -- a Vector2Like object whose x/y is auto-tracked each frame.
xyzorientationXorientationYorientationZpanningModel'equalpower''HRTF'distanceModel'linear''inverse''exponential'refDistancemaxDistancerolloffFactorconeInnerAngleconeOuterAngleconeOuterGainfollow位置:(0)、(0)、(0)-- 音效源在世界空间中的位置。
方向:(0)、(0)、(-1)-- 音效源的方向向量。
模型:( 或 )、(、、)。
距离:(1)、(10000)、(1)。
锥形区域:(360)、(0)、(0)。
跟踪:(null)-- 带有x/y属性的Vector2Like对象,其位置会在每一帧自动跟踪。
xyzorientationXorientationYorientationZpanningModel'equalpower''HRTF'distanceModel'linear''inverse''exponential'refDistancemaxDistancerolloffFactorconeInnerAngleconeOuterAngleconeOuterGainfollowSoundMarker
SoundMarker
| Property | Type | Default | Description |
|---|---|---|---|
| string | (required) | Unique identifier for the marker |
| number | | Start position in seconds |
| number | (remaining) | Playback duration in seconds |
| SoundConfig | | Default settings for this marker |
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| string | 必填 | 标记点的唯一标识符 |
| number | | 起始位置(秒) |
| number | 剩余时长 | 播放时长(秒) |
| SoundConfig | | 此标记点的默认设置 |
Events
事件
Sound Instance Events (emitted on a Sound object)
音效实例事件(在Sound对象上触发)
| Event Constant | String Value | Callback Args | When |
|---|---|---|---|
| | | Sound starts playing |
| | | Sound is paused |
| | | Sound resumes from pause |
| | | Sound is stopped |
| | | Sound finishes (non-looping) |
| | | Sound loops back to start |
| | | Loop property changes |
| | | Mute state changes |
| | | Volume changes |
| | | Rate changes |
| | | Detune changes |
| | | Seek position changes |
| | | Pan value changes |
| | | Sound is destroyed |
| 事件常量 | 字符串值 | 回调参数 | 触发时机 |
|---|---|---|---|
| | | 音效开始播放时 |
| | | 音效暂停时 |
| | | 音效从暂停恢复时 |
| | | 音效停止时 |
| | | 音效播放完成(非循环)时 |
| | | 音效循环回到开头时 |
| | | 循环属性改变时 |
| | | 静音状态改变时 |
| | | 音量改变时 |
| | | 播放速率改变时 |
| | | 音调偏移改变时 |
| | | 进度位置改变时 |
| | | 声像值改变时 |
| | | 音效被销毁时 |
SoundManager Events (emitted on this.sound
)
this.soundSoundManager事件(在this.sound
上触发)
this.sound| Event Constant | String Value | Callback Args | When |
|---|---|---|---|
| | | |
| | | |
| | | |
| | | Global mute changes |
| | | Global volume changes |
| | | Global rate changes |
| | | Global detune changes |
| | | Audio system unlocked after user interaction |
| | | Single audio key decoded (WebAudio) |
| | | 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();| 事件常量 | 字符串值 | 回调参数 | 触发时机 |
|---|---|---|---|
| | | 调用 |
| | | 调用 |
| | | 调用 |
| | | 全局静音状态改变时 |
| | | 全局音量改变时 |
| | | 全局播放速率改变时 |
| | | 全局音调偏移改变时 |
| | | 用户交互后音频系统解锁时 |
| | | 单个音频key解码完成(WebAudio)时 |
| | | 所有排队音频解码完成(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
)
this.soundBaseSoundManager(this.sound
)
this.soundMethods: , , , , , , , , , , , , , , , , , , , .
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: (0-1), (boolean), (number), (-1200 to 1200), (boolean, default true), (boolean, read-only), (Vector2), (array, private).
volumemuteratedetunepauseOnBlurlockedlistenerPositionsounds方法:, , , , , , , , , , , , , , , , , , , .
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)属性:(0-1)、(布尔值)、(数值)、(-1200到1200)、(布尔值,默认true)、(布尔值,只读)、(Vector2)、(数组,私有)。
volumemuteratedetunepauseOnBlurlockedlistenerPositionsoundsBaseSound (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: (0-1), (boolean), (number), (number), (seconds), (boolean), (-1 to 1), (read-only), (read-only), (seconds), (seconds), (string), / (spatial position, WebAudio only).
volumemuteratedetuneseeklooppanisPlayingisPauseddurationtotalDurationkeyxyAll methods return for chaining.
set*this方法:, , , , , , , , , , , , , , .
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)属性:(0-1)、(布尔值)、(数值)、(数值)、(秒)、(布尔值)、(-1到1)、(只读)、(只读)、(秒)、(秒)、(字符串)、 / (空间位置,仅WebAudio支持)。
volumemuteratedetuneseeklooppanisPlayingisPauseddurationtotalDurationkeyxy所有方法返回以支持链式调用。
set*thisGotchas
注意事项
Browser Autoplay Policy
浏览器自动播放策略
Browsers block audio until user interaction. Phaser handles this automatically:
- WebAudio: starts suspended. Phaser listens for touchstart/touchend/mousedown/mouseup/keydown on
AudioContextto calldocument.body. Thecontext.resume()property is true until unlocked;lockedevent fires once resolved.UNLOCKED - 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 :
UNLOCKEDjs
if (this.sound.locked) {
this.sound.once('unlocked', () => {
this.sound.play('bgm');
});
} else {
this.sound.play('bgm');
}浏览器会阻止音频自动播放,直到用户进行交互。Phaser会自动处理此问题:
- WebAudio:初始为暂停状态。Phaser会监听
AudioContext上的touchstart/touchend/mousedown/mouseup/keydown事件,调用document.body。context.resume()属性在解锁前为true;解锁后会触发locked事件。UNLOCKED - HTML5 Audio:锁定的音频标签会将所有操作加入队列,直到第一次触摸操作后重新执行。
你无需手动处理解锁。如需知道何时准备就绪,可监听事件:
UNLOCKEDjs
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: . 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音质极佳但对旧浏览器支持有限。
this.load.audio('bgm', ['assets/bgm.ogg', 'assets/bgm.mp3'])HTML5 Audio Simultaneous Playback
HTML5 Audio同时播放
HTML5 Audio uses a pool of tags. Specify when loading for simultaneous playback: . Default is 1. If all tags are in use and is true (default), the sound with the most progress is hijacked. WebAudio has no such limitation.
<audio>instancesthis.load.audio('shot', 'assets/shot.mp3', { instances: 4 })manager.overrideHTML5 Audio使用标签池。加载时需指定数量以支持同时播放:。默认值为1。如果所有标签都在使用中且为true(默认),则会抢占进度最靠前的音效。WebAudio无此限制。
<audio>instancesthis.load.audio('shot', 'assets/shot.mp3', { instances: 4 })manager.overrideiOS/Safari Specifics
iOS/Safari特定问题
- not supported on iOS/Safari, so
StereoPannerNodehas no audible effect (events still fire).pan - iOS 17/18+ can interrupt audio on background. Phaser handles this via /
context.suspend()on thecontext.resume()game event.VISIBLE - and spatial audio are WebAudio-only.
setListenerPosition()
- iOS/Safari不支持,因此
StereoPannerNode无听觉效果(事件仍会触发)。pan - iOS 17/18+会在后台中断音频。Phaser通过游戏事件调用
VISIBLE/context.suspend()处理此问题。context.resume() - 和空间音频仅支持WebAudio。
setListenerPosition()
WebAudio Context Reuse
WebAudio上下文复用
For SPAs that recreate the game without a full page reload, pass in the game config. You can also swap contexts at runtime via (WebAudio only).
audio: { context: existingAudioContext }this.sound.setAudioContext(newContext)对于不刷新页面就重新创建游戏的单页应用,可在游戏配置中传入。也可在运行时通过切换上下文(仅WebAudio支持)。
audio: { context: existingAudioContext }this.sound.setAudioContext(newContext)Sound Manager is Shared (Global)
SoundManager是全局共享的
There is one SoundManager per game, not per scene. 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.
this.sound每个游戏仅有一个SoundManager,而非每个场景一个。所有场景中的都指向同一个管理器。场景关闭时音效不会自动清理 -- 如需清理必须手动停止/移除。循环播放的音效会在场景切换后继续播放,除非显式停止。
this.soundFire-and-Forget vs Persistent Sounds
一次性播放 vs 持久音效
this.sound.play(key)this.sound.add(key)this.sound.play(key)this.sound.add(key)Spatial Audio is WebAudio Only
空间音频仅支持WebAudio
The 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降级方案,请勿依赖空间定位作为游戏关键音频提示。
sourceWeb Audio Analyser (WebAudio Only)
Web Audio分析器(仅WebAudio支持)
Access the underlying to create an for frequency/waveform visualization:
AudioContextAnalyserNodejs
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 effectsThis only works with the WebAudioSoundManager. Check exists before using.
this.sound.context访问底层创建以实现频率/波形可视化:
AudioContextAnalyserNodejs
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.contextSource File Map
源码文件映射
| File | Purpose |
|---|---|
| Factory: picks WebAudio, HTML5, or NoAudio manager |
| Base manager: add, play, get, stop/pause/resume all, global volume/rate/detune |
| Base sound: play/pause/resume/stop, markers, config, calculateRate |
| WebAudio manager: AudioContext, gain nodes, unlock, spatial listener, decodeAudio |
| WebAudio sound: buffer sources, spatial/panner nodes, seek, all properties |
| HTML5 manager: audio tag pooling, locked queue, override |
| HTML5 sound: tag-based playback, limited feature set |
| No-op manager for environments without audio |
| All sound event constants (PLAY, STOP, COMPLETE, etc.) |
| SoundConfig type definition |
| SoundMarker type definition |
| SpatialSoundConfig type definition |
| AudioSpriteSound type definition |
| 文件 | 用途 |
|---|---|
| 工厂类:选择WebAudio、HTML5或NoAudio管理器 |
| 基础管理器:添加、播放、获取、批量停止/暂停/恢复、全局音量/速率/音调偏移控制 |
| 基础音效类:播放/暂停/恢复/停止、标记点、配置、速率计算 |
| WebAudio管理器:AudioContext、增益节点、解锁、空间监听、音频解码 |
| WebAudio音效类:缓冲源、空间/声像节点、进度跳转、所有属性控制 |
| HTML5管理器:音频标签池、锁定队列、抢占机制 |
| HTML5音效类:基于标签的播放、有限功能集 |
| 无音频环境的空操作管理器 |
| 所有音效事件常量(PLAY、STOP、COMPLETE等) |
| SoundConfig类型定义 |
| SoundMarker类型定义 |
| SpatialSoundConfig类型定义 |
| AudioSpriteSound类型定义 |