You're going to want to use java.applet.AudioClip to play your sounds. I find it's definitely the best way in Java2D. It's fairly simple. Basically you create the AudioClip and then call one of three methods.
AudioClip shot = new AudioClip("sounds/shot.wav");
shot.play(); //Plays the sound once
shot.stop(); //stops playing the sound
shot.loop(); //keeps playing the sound until stopped
And that should work fine, very simply. It sounds like you may be getting problems because you have not preloaded the sound. Do so by making a SoundManager class that holds all your sounds.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import java.applet.AudioClip; public class SoundManager { private AudioClip[] sounds; public static final int SHOT_SND = 0; public static final int DIE_SND = 1;
public SoundManager() { sounds = new AudioClip[2]; sounds[SHOT_SND] = new AudioClip("sounds/shot.wav"); sounds[DIE_SND] = new AudioClip("sounds/die.aif"); }
public void play(int sound) { sounds[sound].play(); }
public void stop(int sound) { sounds[sound].stop(); }
public void loop(int sound) { sounds[sound].loop(); } } |
Understand? Make sense?