Nemanja Kovacevic
Nemanja Kovacevic

Reputation: 43

audio reading in jar executable file

in my eclipse when i run it, everything works fine and audio is okay, but i have problem when i create my .jar executable file. Audio file is in my package and i read it with getResourceAsStream so i just want to let you know. Here is problem..

InputStream input = getClass().getResourceAsStream("/optician/funny-doorbell.wav");
AudioInputStream audioIn;
try{
Clip clip;
audioIn = AudioSystem.getAudioInputStream(input);
clip=AudioSystem.getClip();
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException | IOException e1) {
e1.printStackTrace();
} catch (LineUnavailableException e1) {
e1.printStackTrace();
}

In this first case when i run with eclipse, it works fine, but when i run .jar executable file i get : reset/mark not supported.

Second case is everything same but :

BufferedInputStream input = (BufferedInputStream) getClass().getResourceAsStream("/optician/funny-doorbell.wav");

So everything is same, point is this that i now try with BufferedInputStream but the problem i get now is : Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: sun.new.www.protocol.jar.JarURLConnection$JarURLInputStream cannot be cast to java.io.BufferedInputStream

I tried in linux and windows but it doesn't works. Where is the problem ?

Upvotes: 1

Views: 440

Answers (1)

Firefly
Firefly

Reputation: 5525

I think this question has been asked and answered before. See the accepted answer here for a detailed explanation: java.io.IOException: mark/reset not supported

That said, I believe you can fix your code by modifying your first line as follows:

InputStream input = new BufferedInputStream(getClass().getResourceAsStream("/optician/funny-doorbell.wav"));

The reason you're seeing a difference in behavior is that in Eclipse, getResourceAsStream is returning an InputStream that supports read/mark. When you run out of a jar, you're getting an implementation of InputStream that does not support read/mark (JarURLInputStream).

If you wrap the returned input stream in a new BufferedInputStream, you'll have read/mark support in the stream when you're running in a jar and your code will work everywhere.

Also, you're getting the ClassCastException because you're trying to cast the input stream returned by getResourceAsStream() to BufferedInputStream. Don't cast it; instead, wrap the returned input stream in a new BufferedInputStream() as I did in the code snippet above.

Upvotes: 1

Related Questions