1

I am making a small game in Java. For this game I just added sounds. So I want to have all my images and audio files in the jar. For pictures this was easy:

new ImageIcon(Main.class.getResource("images/machgd2.png")).getImage()

But for audio it only works when I run the program in Eclipse but not from a jar. I use:

File soundFile = new File(Main.class.getResource(filename).getFile());

So how can I get this file from inside the .jar file?

Update:

OK, got it working, thanks to Andrew! To play the sound I used a class I found on the net, and I found out that class just uses File to get an AudioInputStream, so I dropped the File thing.

Salek
  • 449
  • 1
  • 10
  • 19
totokaka
  • 2,244
  • 1
  • 21
  • 33

2 Answers2

5

When it's in a jar file, it isn't a file on the file system, is it? You'll either have to copy the file out of the jar file into some temporary location, or use APIs which don't require a file (e.g. ones which only need an InputStream or a URL, both of which are easily available from jar files using getResourceAsStream or getResource.).

You haven't shown where you're using soundFile - if you show us which APIs you're trying to use, we can try to suggest an appropriate alternative.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • ones which only need an InputStream *or a URL*, since getResource() returns a URL – JB Nizet Dec 18 '11 at 09:08
  • @JBNizet: Yes, that was why it was only an 'e.g.' - I didn't want to give too many options. Will edit though, as a URL may well be more useful here... – Jon Skeet Dec 18 '11 at 09:15
3

See "Playing a Clip" from the Java Sound info page here at SO to see..

import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;

public class LoopSound {

    public static void main(String[] args) throws Exception {
        URL url = new URL(
            "http://pscode.org/media/leftright.wav");
        Clip clip = AudioSystem.getClip();
        // getAudioInputStream() also accepts a File or InputStream
        AudioInputStream ais = AudioSystem.
            getAudioInputStream( url );
        clip.open(ais);
        // loop continuously
        clip.loop(-1);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // A GUI element to prevent the Clip's daemon Thread
                // from terminating at the end of the main()
                JOptionPane.showMessageDialog(null, "Close to exit!");
            }
        });
    }
}

Which, you might notice, uses an URL (as returned by getResource()) rather than a File. The method is overloaded to also accept File or InputStream, but I use the URL based version most commonly.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433