Tom Lenc
Tom Lenc

Reputation: 765

Can't play sounds inside a jarfile

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?

Upvotes: 0

Views: 64

Answers (1)

Markovian8261
Markovian8261

Reputation: 899

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();

Upvotes: 1

Related Questions