import { _decorator, Node, AudioClip, AudioSource, director, assetManager } from "cc"; import PlayerDataManager from "./PlayerDataManager"; import ResManager from "./ResManager"; import Resource from "../Config/Resource"; const { ccclass, property } = _decorator; //音频管理器 @ccclass('AudioManager') export default class AudioManager { private _audoSource: AudioSource; private curBgId: number = -1; //当前播放中的背景乐id 用于记录 private lastBgId: number = -1; //上次播放的背景乐id 用于音乐开关切换时播放 private curBgId_confirm: number = -1; //当前播放中的背景乐id 实际播放 private static _I: AudioManager = null; public static get I(): AudioManager { if (!AudioManager._I) { AudioManager._I = new AudioManager(); AudioManager._I.init(); } return AudioManager._I; } private init(){ let audioMgr = new Node(); audioMgr.name = '__audioMgr__'; director.getScene().addChild(audioMgr); director.addPersistRootNode(audioMgr); this._audoSource = audioMgr.addComponent(AudioSource); } /**播放音效 */ PlayEffect(sound, volume:number=1.0) { if (!sound) return; if (!PlayerDataManager.I.IsSoundOn) { return; } let cfgs = Resource.getConfig("Sound") if (!cfgs[sound]) return; let path = `Sound/${cfgs[sound].AssetName}` console.log("PlayEffect:", sound, path) ResManager.I.getBundleAudio(path, (res: AudioClip)=>{ this._audoSource.playOneShot(res, volume) }); } /**播放背景乐 */ PlayMusic(sound, loop:boolean = true, volume:number=1.0) { if (!sound || sound == this.curBgId_confirm) return; let cfgs = Resource.getConfig("Music") if (!cfgs[sound]) return; this.lastBgId = sound; if (!PlayerDataManager.I.IsMusicOn) { return; //这个放在记录后面判断,防止开关打开时,没有记录 } this.StopMusic() this.curBgId = sound; this.curBgId_confirm = sound; let path = `Music/${cfgs[sound].AssetName}` console.log("PlayMusic:", sound, path) ResManager.I.getBundleAudio(path, (res: AudioClip)=>{ this._audoSource.clip = res this._audoSource.play() this._audoSource.volume = volume this._audoSource.loop = loop }); } /**播放远程背景乐 */ PlayRemoteMusic(url, loop:boolean = true, volume:number=1.0) { console.log(`下载远程背景乐: url= ${url}`) assetManager.loadRemote(url, { ext: '.mp3'}, (err, res: AudioClip) => { if (err) { console.log(err); return } console.log(`播放远程背景乐: res= ${res}`) this.StopMusic() this._audoSource.clip = res this._audoSource.play() this._audoSource.volume = volume this._audoSource.loop = loop }) } /**停止播放背景乐 */ StopMusic(){ this._audoSource.stop() this.curBgId = -1 this.curBgId_confirm = -1 } // 重新播放背景乐 ReplayMusic(){ if (this.curBgId > -1) return if (this.lastBgId < 0) return this.PlayMusic(this.lastBgId) } /**暂停播放背景乐 */ PauseMusic(){ this._audoSource.pause() } /**继续播放背景乐 */ ResumeMusic(){ this._audoSource.play() } }