---
name: sound_utils.aicomponent
description: 音频工具函数。提供 safePlaySound() 封装，自动处理音效键不存在时的静默失败，并根据用户设置的静音状态决定是否播放。
triggers: 需要在游戏中安全播放音效（避免缺失音效导致异常）时触发。
---

# 音频工具函数（Sound Utilities）

## Scaffold

`src/game/utils/SoundUtils.ts`

## Imports

- `phaser.aicomponent`（硬依赖：Phaser SoundManager API）

## Skill Definition

```yaml
tools:
  - read_file
  - write_file
inputs:
  - source: src/game/utils/SoundUtils.ts
outputs:
  - safePlaySound: function(scene, key, config?) - safe audio playback wrapper
```

## Recipe

| 决策 | 原因 |
|------|------|
| **静默失败而非抛错** | 资产键缺失（如音效文件未加载）不应中断游戏进程；在试玩广告中，音效缺失是可接受的降级，崩溃不可接受 |
| **尊重静音设置** | SFX 播放必须检查 `settings.soundOn`，否则用户关闭音效后仍会发声，体验问题在发布时暴露 |
| **从 phaser.aicomponent 中抽出** | `phaser.aicomponent` 已内置基础版 `SoundUtils.ts`；本 skill 在需要更复杂音频管理（如 BGM 队列）时作为增强版单独加载 |

## Adapter

- **Role**: `soundUtils` — Phaser 安全音效播放封装
- **Provides**: `safePlaySound(scene, key, config?)` 函数
- **Requires**: `phaser.aicomponent`（硬依赖：Phaser SoundManager API）
- **Consumed by**: `game_scene.aicomponent`、`level_lifecycle.aicomponent`、`path_input_handler.aicomponent` 等所有需要播放 SFX 的 skill
- **Integration point**: `src/game/utils/SoundUtils.ts` —— 在任意 Phaser Scene 中 `import { safePlaySound }` 后使用

## 使用示例

```typescript
import { safePlaySound } from '../utils/SoundUtils';

safePlaySound(this, 'click', { volume: 1.0 });
safePlaySound(this, 'bg', { loop: true, volume: 0.8 });
```
