假设现在我们有两个游戏场景,一个是Home,一个是Game,现在来设置背景音乐。

 

1.创建节点

首先,在Home的场景中,创建一个空节点Audio,注意,这里必须是跟节点

 
node.png

 

2.编写脚本

创建一个脚本AudioManager.js,

cc.Class({
    extends: cc.Component,

    properties: {
        bgMusic:{
            url:cc.AudioClip,
            default: null
        },
    },

    onLoad() {
        cc.game.addPersistRootNode(this.node);
    },

    
    playBgMusic() {
       this.bgMusicChannel = cc.audioEngine.play(this.bgMusic,true,0.5)
    },

    stopBgMusic: function () {        
        if (this.bgMusicChannel !== undefined) {
            cc.audioEngine.stop(this.bgMusicChannel);            
            this.bgMusicChannel = undefined;
        }
    },

});

我们在onLoad()方法中,将该节点设为常驻节点:

 cc.game.addPersistRootNode(this.node);

此时该节点就可以在其他场景中获取到了

3.关联脚本

这一步就不用解释了吧,把该脚本挂载到Audio节点上

4.获取节点

在对应的场景脚本中,获取该常驻节点,调用播放音乐的方法即可

//获取全局播放器
this.AudioPlayer = cc.find("Audio").getComponent("AudioManager");
//停止再开启背景音乐
this.AudioPlayer.stopBgMusic();
this.AudioPlayer.playBgMusic();

转载: https://www.jianshu.com/p/2c0aaa434b44

posted on 2022-10-18 14:08  刘世涛6192  阅读(137)  评论(0编辑  收藏  举报