Planetalia - Java Training

Training and Consulting

Home

Tutorial - Writing a Space Invaders game in Java

  Previous Page - Simple sound Current Page - 28 - Fixing the sound   Next Page - Small optimizations
  Return to the index of free Java tutorials  

Fixing the sound

(c) Alexander Hristov

If you tried our previous program, you probably saw that our framerate dropped drastically, and that the game became jaggy because there was a small delay whenever a sound was played. This happens because the JRE must prepare the audio clip before playing it, and this takes a noticeable time. A better approach - which fixes the problem - is to start a new temporary thread and start playing the sound from this new thread. This allows the rest of the game to continue unbothered. Fortunately, we centralized all requests for playing sounds in the SoundCache class, so now it will be easy to make this change:


1     /**
2      * Curso B?sico de desarrollo de Juegos en Java - Invaders
3      * 
4      * (c) 2004 Planetalia S.L. - Todos los derechos reservados. Prohibida su reproducci?n
5      * 
6      * http://www.planetalia.com
7      * 
8      */
9     package version28;
10    
11    import java.applet.Applet;
12    import java.applet.AudioClip;
13    import java.net.URL;
14    
15    public class SoundCache extends ResourceCache{
16      protected Object loadResource(URL url) {
17        return Applet.newAudioClip(url);
18        
19      }
20      public AudioClip getAudioClip(String name) {
21        return (AudioClip)getResource(name);  
22      }
23      
24 public void playSound(final String name) { 25 new Thread( 26 new Runnable() { 27 public void run() { 28 getAudioClip(name).play(); 29 } 30 } 31 ).start(); 32 } 33 34 public void loopSound(final String name) { 35 new Thread( 36 new Runnable() { 37 public void run() { 38 getAudioClip(name).loop(); 39 } 40 } 41 ).start(); } 42
43 } 44


Do you want to be notified when new tutorials or lessons are published? Press here


Full list of Java source files for this step

Actor.java Bomb.java Bullet.java Invaders.java
Laser.java Monster.java Player.java ResourceCache.java
SoundCache.java SpriteCache.java Stage.java  

Full list of resources

bicho.gif bicho0.gif bicho1.gif bicho2.gif
bombD.gif bombDL.gif bombDR.gif bombL.gif
bombR.gif bombU.gif bombUL.gif bombUR.gif
disparo.gif disparo0.gif disparo1.gif disparo2.gif
explosion.wav misil.gif missile.wav musica.wav
nave.gif oceano.gif photon.wav test.gif
Thumbs.db      

  Previous Page - Simple sound Current Page - 28 - Fixing the sound   Next Page - Small optimizations
  Return to the index of free Java tutorials  

(c) 2004 Planetalia S.L. All rights reserved. Unauthorized reproduction and/or mirroring is not permitted