-2

i made a simple game in java and i want to add a song in the background, i checked everywhere, looked in guids and nothing worked, can some one please tell how to do it? this is the closest i got :

 public static synchronized void playSound(final String url) {
  new Thread(new Runnable() {

    public void run() { 
      try { 
        Clip clip = AudioSystem.getClip();
        AudioInputStream inputStream = AudioSystem.getAudioInputStream(
          Main.class.getResourceAsStream("res/" + url));
        clip.open(inputStream);
        clip.start(); 
      } catch (Exception e) {
      e.printStackTrace;  
      System.err.println(e.getMessage());
      } 
    } 
   }).start();
 }  

this gives me a noll pointer exception, can any one tell me how to fix this code or write a new one that will work? the stack trace is : java.lang.NullPointerException at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(SoftMidiAudioFileReader.java:130) at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1113) at Frame$1.run(Frame.java:59) at java.lang.Thread.run(Thread.java:745)

(line 59 is : AudioInputStream inputStream = AudioSystem.getAudioInputStream(Frame.class.getResourceAsStream("res/" + url));

tal nisan
  • 7
  • 2

2 Answers2

1

since your code is copy/pasted from this thread , which has good reviews How can I play sound in Java?

the file must be in the wrong directory (and did you change path/to/sounds to the path where the sound is ? ;) )

Community
  • 1
  • 1
Bart Hofma
  • 644
  • 5
  • 19
0

Place the sound clip you are trying to reference in the same folder as the source code. After you have done that replace "/path/to/sounds" with the name of the sound clip.

My suggestion to you, is to research the topic of relative path references. This will help you drastically when it comes to situations such as this.

Regards,

Kurtis

  • yea i did place it in res, and put the right file location, just wrote wrong on the qutsion, but this is still not working, why? – tal nisan Dec 08 '14 at 19:10