pinball/assets/_Game/Scripts/Manager/SoundManager.ts

121 lines
3.3 KiB
TypeScript

import { _decorator, AudioClip, AudioSource, Component, Node } from 'cc';
import Singleton from '../Singleton';
import { Howl } from 'howler';
const { ccclass, property } = _decorator;
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>('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, volume = 1, loop = true, rate = 1) {
this._audioSourceBgm?.stop();
this._audioSourceBgm = new globalThis.Howl({
src: audio.nativeUrl,
volume: volume,
loop: loop,
rate: rate,
mute: this._isMute,
});
this._audioSourceBgm.play();
}
public setPlayRateBGM(rate: number) {
this._audioSourceBgm.rate(rate);
}
public playSfx(audioClip: AudioClip, volume = 1, loop = false) {
let soundSource = this._audioSourcesSfx[audioClip.uuid];
if (soundSource) {
soundSource.volume = volume;
soundSource.source.loop = loop;
if (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 = loop;
soundSource.source.volume = volume;
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];
}
}