3

I made this method to play audio in my class and it works fine. but for some reason when i export it to a jar file nothing happens. I tried other solutions but i just get null-pointer exceptions. does anyone have an idea what i'm doing wrong

public void welcome(){
        try { 
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("sound/garage1.wav").getAbsoluteFile());
            Clip clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            clip.start();
        } catch(Exception ex) {
            System.out.println("Error with playing sound.");
            ex.printStackTrace();
        }
 }
GôTô
  • 7,974
  • 3
  • 32
  • 43
  • Any error or exception? – RamPrakash Feb 03 '17 at 13:09
  • The folder probaby didn't follow, so the file doesn't exist (you can always open a `.jar` since it is a simple archive) to check – AxelH Feb 03 '17 at 13:11
  • Possible duplicate of [Runnable JARs missing Images/Files (Resources)](http://stackoverflow.com/questions/8960381/runnable-jars-missing-images-files-resources) – AxelH Feb 03 '17 at 13:15
  • You will find some interesting information in [that answer](http://stackoverflow.com/a/9866659/4391450) – AxelH Feb 03 '17 at 13:16

1 Answers1

4

if you load the file like this (not as ressource of a class), the folder "sound" containing the "garage1.wav" has to be located in the working directory when you execute the jar, because new File("") points to the working directory. For example: if you execute the jar with a double click on it, the folder "sound" must have the same parent folder as the jar.

Calculator
  • 2,769
  • 1
  • 13
  • 18
  • thanks that solved my problem !!, but is there a way to do it without the jar being in the same parent folder as the sound folder? – rocheandley kwidama Feb 03 '17 at 14:25
  • 2
    @rocheandleykwidama Of course. You can define an arbitrary relative or absolute file path replacing "sound/garage1.wav". If you want the sound file to be located inside of the jar, have a look on [play .wav file from jar as resource using java](http://stackoverflow.com/q/8425481). – Calculator Feb 03 '17 at 14:33