How to Add music to a Phaser3 Game

Ready to add some music to a phaser3 project? Let's start with our 'Hello World' program and attach some music.

<html lang="en"> 

<head> 
    <meta charset="UTF-8" />
    <title>Music Example</title>

    <script src="phaser.min.js"></script>
	
    <style type="text/css">

        body {
            margin: 0;
        }

    </style>
</head>

<body>

<script>

    var config = {
        type: Phaser.AUTO,
        width: 800,
        height: 600,
        scene: {
            preload: preload,
            create: create,
        }
    };

    var music;

    var game = new Phaser.Game(config);

function preload() {
    this.load.audio('myMusic', 'a_song.ogg');//Does not have to be an ogg file
}

   
function create() {
   
  music = this.sound.add('myMusic');
  music.play();
      

  text = this.add.text(200, 200, 'Hello World', { fontSize: '50px', fill: '#9999ff' });
      

}//create

</script>

</body>
</html>

And if you want your music to play on a continuous loop, then set the loop property to true.

music = this.sound.add('myMusic');
music.loop = "true";
music.play();


Comments

Popular Posts