Hi all. It's my first time working with sound in Java and I feel like I'm back in high school trying to figure out a monster. I wanted to create sound effects for my game. I started with this class, that seemed very helpful at first:
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| import java.io.*; import java.net.URL; import javax.sound.sampled.*;
public enum SoundEffect { EXPLODE("explode.wav"), GONG("gong.wav"), SHOOT("shoot.wav"); public static enum Volume { MUTE, LOW, MEDIUM, HIGH } public static Volume volume = Volume.LOW; private Clip clip; SoundEffect(String soundFileName) { try { URL url = this.getClass().getClassLoader().getResource(soundFileName); AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url); clip = AudioSystem.getClip(); clip.open(audioInputStream); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } } public void play() { if (volume != Volume.MUTE) { if (clip.isRunning()) clip.stop(); clip.setFramePosition(0); clip.start(); } } static void init() { values(); } } |
It does work pretty well. But let's take one specific case. When I walk into a wall it's supposed to play a sound. That works, but if I hold the key down, sometimes the sound does not play. Seems like something is getting overwhelmed playing the sound over and over. It's not a total deal breaker for using this code, but I just wanted to know if there's any way to fix it. Also the sounds in my game are very simple, and only come from one basic direction, so I don't think I should have to use anything fancy like JOAL. However I could be wrong so let me know?
EDIT - That is not my code. I simply used it as a jumping off point. It is relatively unchanged in my game, aside from the constructor calls up top.
EDIT 2 - Well I figured out how to get past my problem for now, in a way I like, but I'd still like to know if there is anything I can do in the future if I need to rapidly play sounds. Thanks!