|
| 1 | +import Phaser from "phaser"; |
| 2 | + |
| 3 | +type MusicStartOptions = { |
| 4 | + loop?: boolean; |
| 5 | +}; |
| 6 | + |
| 7 | +type PlaySfxOptions = Phaser.Types.Sound.SoundConfig; |
| 8 | + |
| 9 | +type SoundWithRate = Phaser.Sound.BaseSound & { setRate: (rate: number) => Phaser.Sound.BaseSound }; |
| 10 | +type SoundWithMute = Phaser.Sound.BaseSound & { setMute: (muted: boolean) => Phaser.Sound.BaseSound }; |
| 11 | + |
| 12 | +const hasSetRate = (sound: Phaser.Sound.BaseSound): sound is SoundWithRate => "setRate" in sound; |
| 13 | +const hasSetMute = (sound: Phaser.Sound.BaseSound): sound is SoundWithMute => "setMute" in sound; |
| 14 | + |
| 15 | +export class AudioManager { |
| 16 | + currentMusic?: Phaser.Sound.BaseSound; |
| 17 | + musicVolume = 0.35; |
| 18 | + sfxVolume = 0.7; |
| 19 | + private muted = false; |
| 20 | + |
| 21 | + playSfx(scene: Phaser.Scene, key: string, opts: PlaySfxOptions = {}): Phaser.Sound.BaseSound { |
| 22 | + const volume = (opts.volume ?? 1) * this.sfxVolume; |
| 23 | + const sound = scene.sound.add(key, { ...opts, volume }); |
| 24 | + |
| 25 | + if (hasSetMute(sound)) { |
| 26 | + sound.setMute(this.muted); |
| 27 | + } |
| 28 | + sound.once(Phaser.Sound.Events.COMPLETE, () => { |
| 29 | + sound.destroy(); |
| 30 | + }); |
| 31 | + sound.play(); |
| 32 | + |
| 33 | + return sound; |
| 34 | + } |
| 35 | + |
| 36 | + startMusic(scene: Phaser.Scene, key: string, { loop = true }: MusicStartOptions = {}): Phaser.Sound.BaseSound { |
| 37 | + if (this.currentMusic && this.currentMusic.key === key && this.currentMusic.isPlaying) { |
| 38 | + return this.currentMusic; |
| 39 | + } |
| 40 | + |
| 41 | + this.stopMusic(); |
| 42 | + |
| 43 | + const music = scene.sound.add(key, { loop, volume: this.musicVolume }); |
| 44 | + if (hasSetMute(music)) { |
| 45 | + music.setMute(this.muted); |
| 46 | + } |
| 47 | + music.play(); |
| 48 | + this.currentMusic = music; |
| 49 | + |
| 50 | + music.once(Phaser.Sound.Events.DESTROY, () => { |
| 51 | + if (this.currentMusic === music) { |
| 52 | + this.currentMusic = undefined; |
| 53 | + } |
| 54 | + }); |
| 55 | + |
| 56 | + return music; |
| 57 | + } |
| 58 | + |
| 59 | + stopMusic(): void { |
| 60 | + if (!this.currentMusic) { |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + this.currentMusic.stop(); |
| 65 | + this.currentMusic.destroy(); |
| 66 | + this.currentMusic = undefined; |
| 67 | + } |
| 68 | + |
| 69 | + setMusicRate(rate: number): void { |
| 70 | + if (this.currentMusic && hasSetRate(this.currentMusic)) { |
| 71 | + this.currentMusic.setRate(rate); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + setMuted(muted: boolean): void { |
| 76 | + this.muted = muted; |
| 77 | + if (this.currentMusic && hasSetMute(this.currentMusic)) { |
| 78 | + this.currentMusic.setMute(muted); |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments