Reputation: 128
So I've been making a game, and have decided that I want to a sound effects for it. I can play sounds just fine until I package the class files and (and the wav audio files) the into the jar, and only to find that it can't find the files. I am using getClass().getResource("sounds/enemyExplode.wav")
to get the file. Is there a different method that I should be using?
Thanks in advance!
Upvotes: 5
Views: 1757
Reputation: 995
Within a jar, I've learned it works better to use getResourceAsStream(). If you are using AudioInputStream then it works just as well:
AudioInputStream ais = AudioSystem.getAudioInputStream
(Sound.class.getResourceAsStream(fileName));
And this is how the file name should look (soundbase, is in your case "sounds"):
"/" + soundbase + "/" + file.wav
I have a fully functioning sound class that I found online some place a few years ago that works quite well. I slightly modified it, but it should work in most scenarios if you want me to post it.
Upvotes: 3
Reputation: 7722
first, make sure your sounds are actually packaged in the jar file. you can open the jar file with any archiver that supports zip.
secondly, when you call blabla.getClass().getResources("sounds")
you operate relative to the class path of blabla, that means that the full package name in which blabla is contained will be prepended to "sound" to resolve the full path inside the jar file.
if you want to specify an absolute path , just prepend a slash to the path: blabla.getClass().getResources("/sound")
Upvotes: 1
Reputation: 15409
The class loader's getResource() method operates on resources within the class path. If you have the sounds at the following location in the JAR:
/sounds/enemyExplode.wav
Then you need to use a leading slash in front of the path (just as above) in that call.
Remember a JAR file is really nothing more than a packaged up version of the filesystem (same format as a zip) and the class loader operates upon it as it would if it were a filesystem.
Upvotes: 3