Search code examples
javaaudiojavasound

Java - How do I load a .wav from inside the jar?


I've been trying to play a .wav file in my java project and I got it working....or so I thought. When I exported it to an executable jar file, the sounds won't play unless they're in the same directory as the jar file. I want it to load the sounds that a inside of the jar file. Here's the code I'm using right now:

    void PlaySound(String filename) {
        try (InputStream in = getClass().getResourceAsStream(filename)) {
            try (AudioInputStream audioIn = AudioSystem.getAudioInputStream(in)) {
                Clip clip = AudioSystem.getClip();
                clip.open(audioIn);
                clip.start();
            }

        } catch (Exception e) {
           e.printStackTrace();
       }
    }

Solution

  • I needed to change it to:

    void PlaySound(String filename) {
            try (InputStream in = getClass().getResourceAsStream(filename)) {
                InputStream bufferedIn = new BufferedInputStream(in);
                try (AudioInputStream audioIn = AudioSystem.getAudioInputStream(bufferedIn)) {
                    Clip clip = AudioSystem.getClip();
                    clip.open(audioIn);
                    clip.start();
                }
            } catch (Exception e) {
               e.printStackTrace();
           }
        }
    

    But I actually got this solution from here: java.io.IOException: mark/reset not supported