I'm making a program, and I want it to start playing sounds when it opens. I figured the easiest way for me to do this is to embed the .wav file in the src folder in my jar. I have placed the file in a packaged called files
and all the other files i am using such as pictures are in that package and they all work fine. my method for playing sounds is here:
public static void playSound(String dir, int loopTimes) throws Exception {
URL url = new File(dir).toURI().toURL();
Clip clip = AudioSystem.getClip();
// getAudioInputStream() also accepts a File or InputStream
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
if (loopTimes == -1)
loopTimes = Clip.LOOP_CONTINUOUSLY;
clip.loop(loopTimes);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
}
});
}
and it works for playing the sounds when they are on my desktop, my documents, anywhere else. the path that i am inputting for playing the sound is "files/FBP.wav"
were FBP is the name of the file. i havent been able to find any solutions on google, and i have the feeling that it is because it is in the JAR. I have also just simply tried this:
if(new File("files/FBP.wav").exists()){
System.out.println("EXISTS!");
}
System.exit(0);
and it never printed out that it exists. i have made sure that it is in the bin folder as well. i am using eclipse. the error i get is filenotfoundexception
. any help is appreciated! Thanks in advance!
Replace:
URL url = new File(dir).toURI().toURL();
With:
URL url = MySoundClassName.class.getClassLoader().getResource(dir);
Or for non-static methods:
URL url = getClass().getClassLoader().getResource(dir);