I'm a bit confused about loading and playing sound effects. My game is setup in different states, first the Preloader state makes sure all images and sounds are loaded. The GameState is the main game, this state is re-started for each next level. There are different levels but the state is the same, it just changes a _levelIndex
variable and uses the same state.
The GameState adds the needed audio to the game in the .create()
function, and this create-function is called every time the GameState is started. See code below
mygame.Preloader.prototype = {
preload: function(){
this.loadingbar_bg = this.add.sprite(80, 512, "loadingbar_bg");
this.loadingbar_fill = this.add.sprite(80, 512, "loadingbar_fill");
this.load.setPreloadSprite(this.loadingbar_fill);
// load sounds
this.load.audio("button", ["snd/button.mp3", "snd/button.ogg"]);
this.load.audio("punch", ["snd/punch.mp3", "snd/punch.ogg"]);
this.load.audio("coin", ["snd/coin.mp3", "snd/coin.ogg"]);
},
create: function() {
this.state.start("MainGame");
},
};
mygame.GameState.prototype = {
create: function() {
this.stage.backgroundColor = "#f0f";
// etc.
// sound effects
this.sound1 = this.game.add.audio("button");
this.sound2 = this.game.add.audio("punch");
this.sound3 = this.game.add.audio("coin");
//etc.
},
update: function() {
if (hitFace) {
this.sound2.play();
hitFace = false;
};
},
doNextLevel: function() {
this.sound1.play();
this._levelIndex++; // next level
this.state.start("MainGame"); // restart this state
},
//etc.
};
The problem is that when I play the punch sound a couple of times in a row a couple of seconds apart, the console gives this warning (which Phaser raises in code here)
Phaser.Sound: Audio source already exists
This warning appears even when the GameState is started for the first time.
I suspect that it has to do with decoding the mp3 and ogg sounds. Do I have to decode the sound samples every time the player starts (or restarts) a level i.e. restart the GameState? In other words, if the GameState will be .create()
each time a level is (re)started and the audio samples are added using game.add.audio
, will the decoded samples from the previous level be destroyed and have to be reloaded/decoded each time? That seems wasteful, what is the best way to do this? So my questions are:
- What does this message "Audio source already exists" mean ? Or should I ignore it?
- if I want to use sounds in a state, do I have to re-add them every time the state is started and
.create()
is called ? - also somewhat related, if I want to use the same sound sample in multiple different States (menu, game, options etc.) do I have to do
game.add.audio()
for the same sound for each state?