import { _decorator, AudioClip, AudioSource, Component, Node } from 'cc'; import Singleton from '../Singleton'; import { Howl } from 'howler'; const { ccclass, property } = _decorator; export class SoundSource { public source: AudioSource; private _volume = 1; public get volume() { return this._volume; } public set volume(value: number) { this._volume = value; if (!this.mute) this.source.volume = value; } private _mute = false; public get mute() { return this._mute; } public set mute(value: boolean) { if (value) { this.source.volume = 0; } else { this.source.volume = this.volume; } this._mute = value; } public play() { if (this.source.playing) { this.source.playOneShot(this.source.clip, this.mute ? 0 : this.volume); return; } this.source.play(); } public stop() { this.source.stop(); } } @ccclass('SoundManager') export class SoundManager extends Singleton('SoundManager') { private _audioSourcesSfx: { [key: string]: SoundSource } = {}; private _audioSourceBgm: Howl; private _isMute = false; public toggleMute(): boolean { this._isMute = !this._isMute; this.setMute(this._isMute); return this._isMute; } public setMute(mute: boolean) { this._isMute = mute; this._audioSourceBgm.mute(this._isMute); for (const key in this._audioSourcesSfx) { this._audioSourcesSfx[key].mute = this._isMute; } } public playBGM(audio: AudioClip, opts?: { volume?: number; loop?: boolean; rate?: number }) { this._audioSourceBgm?.stop(); this._audioSourceBgm = new globalThis.Howl({ src: audio.nativeUrl, volume: opts?.volume || 1, loop: opts?.loop || true, rate: opts?.rate || 1, mute: this._isMute, }); this._audioSourceBgm.play(); } public setPlayRateBGM(rate: number) { this._audioSourceBgm.rate(rate); } public playSfx(audioClip: AudioClip, opts?: { volume?: number; loop?: boolean }) { let soundSource = this._audioSourcesSfx[audioClip.uuid]; if (soundSource) { soundSource.volume = opts?.volume || 1; soundSource.source.loop = !!opts?.loop; if (soundSource.source.playing && !!opts?.loop) return; soundSource.play(); return; } soundSource = new SoundSource(); const audioSource = new AudioSource('audioSourceSfx:' + audioClip.name); soundSource.source = audioSource; soundSource.source.playOnAwake = false; soundSource.source.clip = audioClip; soundSource.source.loop = !!opts?.loop; soundSource.source.volume = opts?.volume || 1; soundSource.mute = this._isMute; this._audioSourcesSfx[audioClip.uuid] = soundSource; soundSource.play(); } public stopBgm() { this._audioSourceBgm.stop(); } public stopSfx(audioClip: AudioClip) { this._audioSourcesSfx[audioClip.uuid].stop(); } public stopAllSfxLoop() { for (const key in this._audioSourcesSfx) { this._audioSourcesSfx[key].stop(); } } public findAudioSourcesSfx(audioClip: AudioClip): SoundSource { return this._audioSourcesSfx[audioClip.uuid]; } }