Jump to content

How can you load audio file before the scene start?


notalentgeek
 Share

Recommended Posts

I have this problem, I want for my background music file to be played exactly at the point where my scene starts. I have been looking for the answer and then come to this Phaser official example http://phaser.io/examples/v2/audio/sound-complete. In this example it shows the usage of game.sound.setDecodedCallback();. However, it is not working as what I want.

 

What happened when I use game.sound.setDecodedCallback(this.bgmMusic, this.update, this); is that the game goes directly from my create() function to update() function and then after the this.bgmMusic got decoded the codes execute create() function again. Hence the create() function executed twice. Is there anyway on how I can create so that my game let the this.bgmMusic decoded first then go to update() function of the scene (so the music will play directly as soon the scene starts)?

 

I also have tried to put the game.sound.setDecodedCallback();  in my preload state and then play it in my game state. But it returns missing reference to .play() every time I called this.bgmMusic.play(); in my game state. I do not think putting game.sound.setDecodedCallback();  in different state working.

Link to comment
Share on other sites

Use a separate state, or at least use this.cache.isSoundDecoded to block your update function.

 

You can load the audio in the preload function of that state. Don't start the state that needs the audio until the audio is decoded.

In this example, I'm loading a sound atlas, but it works the same for a single sound:

         constructor: function () {                       this.ready = false;        },        preload: function () {                                 this.game.load.atlasJSONHash( "textureKey", "/path.to.image.file", textureJSON );            this.game.load.audio("soundKey", "/path.to.audio.file"); // media/main.mp3                   },        update: function () {            if (this.cache.isSoundDecoded("soundKey") && this.ready === false) {                this.ready = true;                this.state.start('menu');            }        }   

In this case, the menu state will have full access to the audio. You could do it in a single state by waiting for this.cache.isSoundDecoded, but the code starts to get mess and I prefer having it handled separately.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...