教程 4 — 音效与音乐
$this->sound()(即 SoundManager)负责播放音效和音乐,桌面和浏览器通用。没有声卡时一切静音,绝不会报错。
用 PHP 合成的声音
Synth 可以不用任何文件就生成复古音效:
use JumPHP\Audio\Synth;
if (!$this->sound()->hasSfx('jump')) { // 只做一次
$this->sound()->synth('jump', Synth::sweep(250, 600, 0.12)); // 频率上升
$this->sound()->synth('coin', Synth::sequence([[988, 0.05], [1319, 0.12]])); // 两个音符
$this->sound()->synth('hit', Synth::noise(0.15)); // 噪声
$this->sound()->synth('bass', Synth::tone(110, 0.3, 'triangle')); // square、triangle、sine、saw
}
$this->sound()->playSfx('jump');
使用文件
$this->sound()->loadSfx('explosion', 'assets/sfx/explosion.wav'); // wav、ogg、mp3
$this->sound()->loadMusic('level', 'assets/music/level.ogg');
$this->sound()->playMusic('level');
$this->sound()->stopMusic();
音量
setSfxVolume(0.8)、setMusicVolume(0.5)、setMuted(true):这些设置会随玩家的选项一起保存。选项菜单会把它们做成 ['VOLUME', fn () => ..., null, fn (int $dir) => ...] 这样的菜单行(见菜单)。
也支持 3D 音效(在空间中定位声音):$this->engine->audio3d()。