Reputation: 7520
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?
Upvotes: 1
Views: 1881
Reputation: 7520
As also mentioned here: the documentation for AudioSystem.getAudioInputStream(InputStream)
says:
The implementation of this method may require multiple parsers to examine the stream to determine whether they support it. These parsers must be able to mark the stream, read enough data to determine whether they support the stream, and, if not, reset the stream's read pointer to its original position. If the input stream does not support these operation, this method may fail with an IOException.
Therefore the solution will be
clip.open(AudioSystem.getAudioInputStream(
new BufferedInputStream(getClass().getResourceAsStream("/Sounds/asound.wav"))));
Upvotes: 1
Reputation: 168815
URL url = this.getClass().getResource("/sounds/asound.wav");
The /
prefix when supplied to the class-loader obtained from the class, will cause it to search from the 'root' of the packages.
Then see the code shown on the Java Sound tag Wiki for loading a Clip
and playing it.
Upvotes: 1
Reputation: 8932
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.
Upvotes: 3