import { _decorator, Node, AudioClip, AudioSource, director, assetManager, } from "cc"; import PlayerDataManager from "./PlayerDataManager"; import ResManager from "./ResManager"; import { logger } from "db://assets/Scripts/Main/Common/Logger"; import { Config18x } from "../Config/Config18x"; const { ccclass, property } = _decorator; //音频管理器 @ccclass("AudioManager") export default class AudioManager { private _audoSource: AudioSource; private curBgId: string; //当前播放中的背景乐id 用于记录 private lastBgId: string; //上次播放的背景乐id 用于音乐开关切换时播放 private curBgId_confirm: string; //当前播放中的背景乐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: string, volume: number = 1.0) { if (!sound) return; if (!PlayerDataManager.I.IsSoundOn) { return; } //let cfgs = //if (!cfgs[sound]) return; //let path = `Sound/${cfgs[sound].AssetName}` logger.log("PlayEffect:", sound); ResManager.I.getAudio(sound, (res: AudioClip) => { this._audoSource.playOneShot(res, volume); }); } /**播放背景乐 */ PlayMusic(sound: string, 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}` logger.log("PlayMusic:", sound); ResManager.I.getAudio(sound, (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) { logger.log(`下载远程背景乐: url= ${url}`); assetManager.loadRemote( url, { ext: ".mp3" }, (err, res: AudioClip) => { if (err) { logger.log(err); return; } logger.log(`播放远程背景乐: res= ${res}`); this.StopMusic(); this._audoSource.clip = res; this._audoSource.play(); this._audoSource.volume = volume; this._audoSource.loop = loop; } ); } /**停止播放背景乐 */ StopMusic() { if (this.curBgId != null) { this.lastBgId = this.curBgId; } this._audoSource.stop(); this.curBgId = null; this.curBgId_confirm = null; } // 重新播放背景乐 ReplayMusic(): boolean { if (this.curBgId != null) return false; if (this.lastBgId == null) return false; this.PlayMusic(this.lastBgId); return true; } /**暂停播放背景乐 */ PauseMusic() { this._audoSource.pause(); } /**继续播放背景乐 */ ResumeMusic() { this._audoSource.play(); } }