Sarin Suriyakoon
Sarin Suriyakoon

Reputation: 440

Trying to play sound in Java: NullPointerException

I'm trying to play sound in Java but it doesn't work and I got error message. Here is my Code

public class PlaySoundClip extends JFrame {


public PlaySoundClip() {
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setTitle("Test Sound Clip");
  this.setSize(300, 200);
  this.setVisible(true);

  try {

     URL url = this.getClass().getClassLoader().getResource("click.wav");
     AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);//Line 27
     // Get a sound clip resource.
     Clip clip = AudioSystem.getClip();
     // Open audio clip and load samples from the audio input stream.
     clip.open(audioIn);
     clip.start();
     clip.loop(Clip.LOOP_CONTINUOUSLY);  // repeat forever
  } catch (UnsupportedAudioFileException e) {
     e.printStackTrace();
  } catch (IOException e) {
     e.printStackTrace();
  } catch (LineUnavailableException e) {
     e.printStackTrace();
  }
}

public static void main(String[] args) {
  new PlaySoundClip();//Line 44
 }
}

And I get this error message then I'm not here any sound! How to fix this problem?

Exception in thread "main" java.lang.NullPointerException   
    at com.sun.media.sound.StandardMidiFileReader.getSequence(StandardMidiFileReader.java:205)   
    at javax.sound.midi.MidiSystem.getSequence(MidiSystem.java:836)   
    at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(SoftMidiAudioFileReader.java:174)   
    at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1145)   
    at playsoundclip.PlaySoundClip.<init>(PlaySoundClip.java:27)   
    at playsoundclip.PlaySoundClip.main(PlaySoundClip.java:44)      

Reference from Playing Sound.

Upvotes: 1

Views: 2531

Answers (2)

Leo
Leo

Reputation: 827

Most likely in your build phase there is a list of "resources" that are copied from source tree to the output compiled classes. Usually it is a string of regular expressions like ".txt;.json;…" In your case you need to add ".wav" to it or copy file by hand to the compiler output location.

Most IDEs (Eclipse|IteliJ IDEA) and some ant build scripts have provision for resource copying.

Upvotes: 1

meskobalazs
meskobalazs

Reputation: 16041

Something is wrong with click.wav, it was not found on the classpath, so url became null, hence the NullPointerException.

You should put the click.wav on your classpath, so the program will find it. The most straightforward way is putting into the root folder of the jar file.

Upvotes: 1

Related Questions