Darian Smith
Darian Smith

Reputation: 11

Using audio from resources in a jar file

I've managed to make resources finally get into the jar by using a class with inputstream getting resources from the class, and also adding the images and sounds to a folder within the project directory in eclipse and adding it to the buildpath.

With this images finally run from the within the jar. The same code using AudioinputStream instead of image.io works within the ide when you click run.

But from the jar file there are no sounds.

Here's the code in question

AudioInputStream audioIntStream = AudioSystem.getAudioInputStream(              
Resourceloader.load("images/engine.wav")); 
Clip clip = AudioSystem.getClip(); 
clip.open(audioIntStream); 
clip.loop(Clip.LOOP_CONTINUOUSLY);

title = ImageIO.read(Resourceloader.load("images/title.png") );

The images files from the same directory read from both ide and jar, while as said the audio file only runs from within ide not jar yet jar contains audiofile

Upvotes: 1

Views: 1353

Answers (1)

Karl M. Davis
Karl M. Davis

Reputation: 616

Resource loading in Java can be complicated. However, the following code snippet is almost always what you want:

Thread.currentThread().getContextClassLoader.getResourceAsStream(
  "path/to/resource/from/jar/root.file");

I use that snippet so often that I could type it in my sleep. I'd adjust your code above to use it to load your resources. However, if that doesn't cut it, I'd look into the following:

  1. Check the resources after loading, and throw an Exception if they're null.
  2. Open up your JAR as a ZIP file and ensure that the resource is actually at the path you have listed in your code, starting from the root of the JAR.
  3. Use Ant or Maven to build your JAR, rather than Eclipse's GUI. This will help ensure that your JAR is always built in the same way and reduces the chances for manual mistakes. Using Maven and the standard Maven src/main/resources/ directory is highly recommended.

Upvotes: 2

Related Questions