I try to play two beeps at once during the game (Background music and effect). First, I built this piece of code using a different sound processor in java, which would handle the playback, stop, and loop of sound. This design will play background music or effect, but only one at a time. I surfed the internet and was told to use javax.sound.sampled.Clip to process sounds in order to reuse the same construct (play, stop, loop), but switched it to use javax.sound.sampled.Clip. Now I am completely lost. From what I have read so far, I did everything correctly and did not receive errors in the eclipse editor, but when I run it, I get one of two errors. In eclipse (runs on Linux), a LineUnavailableableException is thrown. In eclipse (runs on Windows 7), I get java.lang.NullPointerException in the loop () section of this code. If you could show me what I am doing wrong, or point me to the relevant documentation, I would appreciate it. I am assuming something with my code that handles Exceptions, but I'm not sure. If you see any other disgusting code errors, please let me know that I strive to be the best programmer I can and really appreciate constructive criticism. Thank you for your time.
import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; public class Sound { private Clip myClip; public Sound(String fileName) { try { File file = new File(fileName); if (file.exists()) { Clip myClip = AudioSystem.getClip(); AudioInputStream ais = AudioSystem.getAudioInputStream(file.toURI().toURL()); myClip.open(ais); } else { throw new RuntimeException("Sound: file not found: " + fileName); } } catch (MalformedURLException e) { throw new RuntimeException("Sound: Malformed URL: " + e); } catch (UnsupportedAudioFileException e) { throw new RuntimeException("Sound: Unsupported Audio File: " + e); } catch (IOException e) { throw new RuntimeException("Sound: Input/Output Error: " + e); } catch (LineUnavailableException e) { throw new RuntimeException("Sound: Line Unavailable: " + e); } } public void play(){ myClip.setFramePosition(0);
source share