1

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Highmastdon
  • 6,960
  • 7
  • 40
  • 68
  • Still doesn't work. For some reason I get a `NullPointerException` at the `getResource`. It is there, the file exists. – Highmastdon Nov 12 '12 at 11:30

3 Answers3

3

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.

nd.
  • 8,699
  • 2
  • 32
  • 42
  • `getResourceAsStream(..)` will typically fail with Java Sound. It seems to need an `InputStream` that can be repositioned, while the stream returned from `getResourceAsStream(..)` is typically not able to. – Andrew Thompson Nov 12 '12 at 10:57
  • You can access the code at: https://bitbucket.org/eXor/starcraft-2-talk/src/02207cf263f8e6ec0a4fbbca47260cf0d6bc7a07/starcraft_2_talk/GameCounter.java?at=master#cl-108 – Highmastdon Nov 12 '12 at 11:34
1
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.

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

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"))));
Community
  • 1
  • 1
Highmastdon
  • 6,960
  • 7
  • 40
  • 68