0

Ok, the title may not be exactly correct, but here is what I mean by that: I have a class with a method that looks like this:

package chess;

import java.io.*;
import sun.audio.*;

public class SoundPlayer

{
  public static void Play(String AudioFile) 

  throws Exception

  {
    // open the sound file as a Java input stream
    InputStream in = new FileInputStream(AudioFile);

    // create an audiostream from the inputstream
    AudioStream audioStream = new AudioStream(in);

    // play the audio clip with the audioplayer class
    AudioPlayer.player.start(audioStream);
  }
}

What I want to do, is to compile a .wav file inside the .jar along all the .java files, and be able to play it with this method. To do this on batch, all I had to do was type the file name, and it used the current directory. I tried that here and it didn't work. So, my final question:

What do I need to type before "/sound.wav" to have my program reffer to it from the source directory? Sorry if I didn't make it clear. I have searched around, but I guess I didn't know what exactly to search for on google, because I didn't find any explanation.

durron597
  • 31,968
  • 17
  • 99
  • 158
RaKXeR
  • 152
  • 2
  • 16

2 Answers2

3

You can use ClassLoader.getResourceAsStream() for that

example:

 // open the sound file as a Java input stream
InputStream in = SoundPlayer.class.getClassLoader().getResourceAsStream("yoursound.wav");

// create an audiostream from the inputstream
AudioStream audioStream = new AudioStream(in);

// play the audio clip with the audioplayer class
AudioPlayer.player.start(audioStream);
David Xu
  • 5,555
  • 3
  • 28
  • 50
-1

If you put your wav files inside your jar, at the root, you should be able to refer to them by its name. I.e

jar
 |-com
    |-your
       |-package
 |-sound.wav

You can access sound.wav on com.your.package.yourclass by referring to it by just its name

perencia
  • 1,498
  • 3
  • 11
  • 19
  • This might be the start of an answer, but it is incomplete, as you've failed to specify what sort of "refer" would work with "its name" as an argument. – Chris Stratton May 02 '14 at 19:11
  • Then I'd say this is not an answer, and not useful. – Chris Stratton May 02 '14 at 19:16
  • What is wrong in what i've said ? The question was how to refer to a sound file inside a jar, if I understood it correctly. The question wasn't that clear also. I don't see why it's not an answer. You should relax. – perencia May 02 '14 at 19:35
  • It's not an answer because you fair to state an access *mechanism* which would accept the name as an argument. – Chris Stratton May 02 '14 at 19:57
  • I'd say it to you before. There's no specific _access mechanism_, you can access that file the same as if it was on the file system. You can do `FileInputStream("sound.wav")`. Where that _access mechanism_ was mentioned on the question ? – perencia May 02 '14 at 20:01