Creating a Flash platform game with Flixel and Flex – Sound and Music

Google+ Pinterest LinkedIn Tumblr +

PLAY THE DEMO

DOWNLOAD THE SOURCE CODE

TUTORIAL INDEX

At this point we have something that resembles a playable game. The big omission has been music and sound effects. Fortunately Flixel, along with the native multimedia capabilities of Flash/Flex, makes adding sounds very easy.

We will start by adding some background music.

  [Embed(source="../media/mode.mp3")] 
  protected var MusicMode:Class;

First we embed an MP3 file. This sample track comes from the Flixel demo game called Mode (actually all of the sound effects and a lot of the graphics used have been sourced from Mode). You can embed any format that Flex recognises, which are listed below.

  • AIFF – Audio Interchange File Format
  • ASND – Adobe Soundbooth
  • AU – Sun File Format
  • MOV – Sound Only QuickTime Movies
  • MP3 – MPEG Layer 3
  • SD2 – Sound Designer 2
  • WAV – Waveform Audio Format
  public function GameState()
  {
   // ...
   
   FlxG.setMusic(MusicMode); 
  }

To play background music you first need to call the FlxGsetMusic function, passing in the embedded music class. An optional parameter called AutoPlay is set to true by default, which means the music will begin playing straight away.

Sound effect work much the same way.

  [Embed(source="../media/asplode.mp3")] 
  protected var SndExplode:Class;

In the Enemy class we have embedded the asplode.mp3 file.

  public override function kill():void
  {
   // ...
   
   FlxG.play(SndExplode);
  }

Then in the kill function (which is called when the Enemy is killed) we use the FlxGplay function.

This pattern of embedding an MP3 and calling the FlxG play function is repeated in the Player and Bullet classes to add sound effects to certain events.

Bullet sound effect code changes:

  [Embed(source="../media/hit.mp3")] 
  protected var SndHit:Class;
  
  [Embed(source="../media/shoot.mp3")] 
  protected var SndShoot:Class;

  public function shoot(X:int, Y:int, VelocityX:int, VelocityY:int):void
  {
   // ...
    
   FlxG.play(SndShoot);
  }

  public override function kill():void
  {
   super.kill();
   FlxG.play(SndHit);
  }

Player sound effect code changes:

  [Embed(source="../media/jump.mp3")] 
  protected var SndJump:Class;
  
  [Embed(source="../media/land.mp3")] 
  protected var SndLand:Class;

  public override function update():void
  {
   // ...   

   if(FlxG.keys.justPressed("X") && !velocity.y)
   {
    velocity.y = -JUMP_ACCELERATION;
    FlxG.play(SndJump);
   }
   
   // ...
  }

  override public function hitFloor(Contact:FlxCore=null):Boolean
  {
   if(velocity.y > 50)
    FlxG.play(SndLand);
   return super.hitFloor();
  }

Share.

About Author

Leave A Reply