tags:

views:

249

answers:

4

The following code is used for playing a sound file in my java applet:

public synchronized void play() {
   try {
          //Here filename is a URL retreived through
          //getClassLoader().getResource()
            InputStream in = new FileInputStream(filename.getFile());
            AudioStream as = new AudioStream(in);
            AudioPlayer.player.start(as); 

    } catch (IOException e) {
            e.printStackTrace();
    }

It works when i run the applet locally using Eclipse, but if I try packaging it in a .jar and running it as an applet in the web browser, it doesn't work. Commenting out this code makes the applet work.

What shall I substitute the above code with so it'll work in the applet?

+3  A: 

Use getClassLoader().getResourceAsStream() instead of new FileInputStream(...). There's no local file involved here (potentially, e.g. when using a jar file). Basically you want to get a stream to the sound data, and when you're fetching a resource from the classpath, getResourceAsStream() is the simplest way of doing that.

(You can use getResource() followed by openStream() if you want, but there's not much point.)

Jon Skeet
+4  A: 

Try using getResourceAsStream() on the ClassLoader instead of new FileInputStream(). This will return an InputStream that you can pass to the AudioStream. So something like:

InputStream in = getClassLoader().getResourceAsStream(getClassLoader().getResource());
AudioStream as = new AudioStream(in)
MrWiggles
+2  A: 

Have a look at the getResourceAsStream() method in the java.lang.ClassLoader class.

This will still work even if you don't have a JAR as long as the relevant files are in your CLASSPATH.

Dave Webb
+4  A: 

Either use ClassLoader.getResourceAsStream or URL.openStream. Remember to close your streams to avoid resource leaks.

Alternatively, check to see if the AudioClip class suits your needs:

  private AudioClip sound = null;

  private AudioClip getSound() {
    if (sound == null) {
      ClassLoader classLoader = TestApplet.class
          .getClassLoader();
      URL url = classLoader.getResource("assets/sound.wav");
      sound = JApplet.newAudioClip(url);
    }
    return sound;
  }
McDowell