I want to access my .wav files which are in a package inside my project.
For example I have two packages:
program
sounds
From inside the program/something.class
I'd like to play the sounds/asound.wav
.
How is this possible?
clip.open(AudioSystem.getAudioInputStream(new File(filename)));
clip.start();
//.... something inbetween
clip.stop();
Here filename
is C:\\projects\\something\\sounds\\
, but how is it possible to just give a relative path to the asound.wav
in the package?
Use ClassLoader.getResourceAsStream
to load resources via the same infrastructure you are using for class loading. Depending on the class loader, this can be a file in a directory, the content of a local JAR file or a remote resource.
getClass().getClassLoader().getResourceAsStream("asound.wav");
As indicated by the name of the method, you will get an InputStream
for the resource, and not a File. If you consider that the resource may be part of another file, such as a JAR file, this makes sense, as File objects always point to single files, and not parts of them.