0

So I use this code:

    ClassLoader classLoader = getClass().getClassLoader();
    File audioFile = new File(classLoader.getResource("pop.wav").getFile());

    AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);

    AudioFormat format = audioStream.getFormat();

    DataLine.Info info = new DataLine.Info(Clip.class, format);

    Clip audioClip = (Clip) AudioSystem.getLine(info);
    audioClip.open(audioStream);
    audioClip.start();

But every time it gives me a NullPointerException. The file (pop.wav) is inside src/res. But if a put it on my desktop and instead of classLoader.getResource("pop.wav").getFile() I put C:/Users/gebruiker/Desktop/pop.wav it works.

  • Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Frakcool Dec 23 '15 at 19:21
  • Possible duplicate of http://stackoverflow.com/questions/8425481/play-wav-file-from-jar-as-resource-using-java –  Dec 23 '15 at 19:30
  • more details on this post: http://stackoverflow.com/questions/573679/open-resource-with-relative-path-in-java – guillaume girod-vitouchkina Dec 23 '15 at 19:33
  • Will you consider accepting the answer? Merry Xmas – Jan Dec 24 '15 at 08:37

1 Answers1

0

Resources are not Files.

Try this:

AudioInputStream audioStream = AudioSystem.getAudioInputStream(getClass ().getResourceAsStream ("/res/pop.wav"));

And of cause check path for that pop.wav. sometimes absolute paths within .jar ( /pop.wav ) are easier to manage.

Jan
  • 13,738
  • 3
  • 30
  • 55