Can't play sounds inside a jarfile

63 views Asked by At

I'm having problems with playing sounds from the jar file. this is the code I have for playing the sounds:

    public class Sounds {

    public static void playClickSound() {
        try {
            Clip clip = AudioSystem.getClip();
            clip.open(AudioSystem.getAudioInputStream(new File("resources/sounds/click.wav")));
            clip.start();
        } catch (Exception exc) {
            exc.printStackTrace(System.out);
        }
    }

    public static void playBuySound() {
        try {
            Clip clip = AudioSystem.getClip();
            clip.open(AudioSystem.getAudioInputStream(new File("resources/sounds/buy.wav")));
            clip.start();
        } catch (Exception exc) {
            exc.printStackTrace(System.out);
        }
    }
}

And other class that is using the Sounds.class file:

//other stuff..
    Sounds.playBuySound();
//another stuff..

But this code doesn't even play it in editor.. I need to make the sounds work even if I export it to a jar file.

Is there any simple solution?

1

There are 1 answers

3
Markovian8261 On BEST ANSWER

You can't simply play a file like you were trying to do, you need to use the getResource method of the class that you are using. For example, try this code

AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(Sounds.class.getResource("/resources/sounds/click.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();