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:
SoundCache.java
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