1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- import { _decorator, AudioClip, AudioSource, Component, Node, tween } from 'cc';
- import { ResourceUtil } from './ResourceUtil';
- import { config } from '../config';
- const { ccclass, property } = _decorator;
- @ccclass('audioManager')
- export class audioManager extends Component {
- public arrSound: any = [];
- public audios_map: Map<string,Node> = new Map;
- public musicVolume: number = 0.8;
- public soundVolume: number = 1;
- private static instance:audioManager =null;
- public static Instance(){
- return this.instance
- }
- protected start(): void {
- audioManager.instance = this
- this.init()
- }
- protected onLoad(): void {
- this.scheduleOnce(()=>{
- this.playMusic(config.AUDIO.home_bgm)
- },3)
- }
- public init(){
- this.audios_map.clear()
- for (const key in config.AUDIO) {
- if (Object.prototype.hasOwnProperty.call( config.AUDIO, key)) {
- const path = config.AUDIO[key];
- ResourceUtil.loadRes(path, AudioClip, (err: any, clip: any)=> {
- if(!err){
- let node = new Node
- node.parent = this.node
- node.addComponent(AudioSource).clip = clip
- this.audios_map.set(path,node)
- }
-
- });
- }
- }
- }
- public playBGM(clip:AudioClip){
- if(this.getSound().clip!=null){
- this.getSound().stop()
- this.getSound().clip = null;
- }
- this.getSound().clip = clip;
- this.getSound().loop = true;
- this.getSound().play()
- }
- public playMusic(path:string){
- if(this.audios_map.get(path)!=null){
- this.playBGM(this.audios_map.get(path).getComponent(AudioSource).clip)
- }else{
- ResourceUtil.loadRes(path, AudioClip, (err: any, clip: any)=> {
- let node = new Node
- node.parent = this.node
- node.addComponent(AudioSource).clip = clip
- this.audios_map.set(path,node)
- this.playBGM(node.addComponent(AudioSource).clip)
- });
- }
- }
- public playSound(path:string,soundVolume:number = null){
- if(path.length<=0){
- return
- }
- let loop:boolean = false
- let play = (node)=>{
- node.getComponent(AudioSource).playOneShot(node.getComponent(AudioSource).clip,soundVolume?soundVolume:this.soundVolume)
- }
- if(this.audios_map.get(path)){
- play(this.audios_map.get(path))
- }
- ResourceUtil.loadRes(path, AudioClip, (err: any, clip: AudioClip)=> {
- let node = new Node
- node.parent = this.node
- node.addComponent(AudioSource).clip = clip
- this.audios_map.set(path,node)
- play(node)
- });
- }
- getSound(){
- if(this.node.getComponent(AudioSource)!=null){
- return this.node.getComponent(AudioSource)
- }
- return this.node.addComponent(AudioSource)
- }
- }
|