any help on what would be a correct way of keeping background music playing (creator 1.7.0) while changing scenes. My current “game” has two scenes “Menu” and “Game” and I use cc.director.loadScene to change scenes. I’ve tried:
Creating loader scene, in which I added AudioSource to nodetree and set loader scenes node as persistent (cc.game.addPersistRootNode). Then changed scene to Menu … This caused black screen after initial loader, then audio played for few seconds and then it stopped
Adding empty node+audiosource to Menu scene and setting that node as persistent in onload method … Audio died when switching to game scene
Programmatically creating new node in Menu-scene, adding audiosource component to it and trying to set that node as persistent … didn’t work either.
I did manage to keep audio playing with this piece of code (basically setting window.audioplayer variable), but somehow it seems quite hacky:
properties: { song1: { default: null, url: cc.AudioClip } }
....
onload() { ...
var node = new cc.Node();
node.name = "AudioPlayer";
node.addComponent(cc.AudioSource);
var ac = node.getComponent(cc.AudioSource);
ac.clip = this.song1;
ac.play();
window.audioPlayer = node;
... }
if (!GlobalData.TitleInitialized) {
GlobalData.TitleInitialized = true;
// Start music if Music is "On"...
if (GlobalData.Music) {
GlobalData.MusicAudioID = cc.audioEngine.playMusic(this.musicProp, true);
}
}
In the Options you can enable/disable the music, here is code for the button:
GlobalData.Music = !GlobalData.Music;
GlobalData.saveSettings();
if ((GlobalData.MusicAudioID == -1) && (GlobalData.Music))
GlobalData.MusicAudioID = cc.audioEngine.playMusic(this.musicProp, true);
if (!GlobalData.Music)
cc.audioEngine.pause(GlobalData.MusicAudioID);
else
cc.audioEngine.resume(GlobalData.MusicAudioID);
And when the game starts, the onLoad event of the Game scene:
if (GlobalData.Music) {
cc.audioEngine.stopMusic(GlobalData.MusicAudioID);
this.localMusicID = cc.audioEngine.playMusic(this.musicProp, true);
}
And finally when we go back to the Title scene:
if (GlobalData.Music) {
cc.audioEngine.stopMusic(this.localMusicID);
GlobalData.MusicAudioID = cc.audioEngine.playMusic(this.titleMusicProp, true);
}