Loading Audio

If you load an audio file outside of preload(), it will not instantly be available. You have to wait for the filecomplete event.

create() {
  let songLoader = this.load.audio('song', ['assets/sounds/0781.ogg'])
  songLoader.on('filecomplete', () => this.sound.add('song').play())
  songLoader.start()
}

Or if you want to use async/await:

async create() {

  const asyncLoader = loaderPlugin => {
    return new Promise(resolve => {
      loaderPlugin.on('filecomplete', () => resolve()).on('loaderror', () => resolve())
      loaderPlugin.start()
    })
  }

  await asyncLoader(this.load.audio('song', ['assets/sounds/0781.ogg']))
  this.sound.add('song').play()
}
2 Likes