Reputation:
none of the answers I found to this question worked, so I have to ask here: I'm using Eclipse and I have a program that I export as a runnable jar, and it plays an audio, but the audio has to be in the same folder as the exported jar file or else it doesn't play. How can I package it into the runnable jar so that it doesn't need the audio to actually be there? PS: I'm doing things the old-fashioned way so not using a build system (Maven or Gradle) this is my code; it plays an audio file when a button is pressed:
AudioFormat audioformat = null;
DataLine.Info info = new DataLine.Info(Clip.class, audioformat);
try {
Clip audioclip = (Clip) AudioSystem.getLine(info);
File audio1 = new File("audiofile.wav");
AudioInputStream audiostream = AudioSystem.getAudioInputStream(audio1);
audioformat = audiostream.getFormat();
audioclip.open(audiostream);
audioclip.start();
audiostream.close();
} catch (LineUnavailableException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnsupportedAudioFileException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
```
Upvotes: 0
Views: 108
Reputation: 103273
use getResourceAsStream
:
class Example {
void getAudioData() {
try (InputStream in = Example.class.getResourceAsStream("file.mp3")) {
// pass 'in' to your music player of choice.
// NB: If you can only pass 'File' or 'Path' objects, and not
// URL or InputStream objects, get another music playing library.
}
}
void alternateForm() {
musicPlayer.play(Example.class.getResource("file.mp3"));
// Use this form if your music player takes URLs and not InputStreams.
}
}
Where your jar ends up looking like this:
jar tvf Mobbs8app.jar
1234 Wed 19 Jan 20:00 com/foo/mobbs8/Main.class
1234 Wed 19 Jan 20:00 com/foo/mobbs8/Example.class
1234 Wed 19 Jan 20:00 com/foo/mobbs8/file.mp3
Where Main.class
here is your main class, with package header "package com.foo.mobbs8;" - getResourceAsStream
looks in the same 'directory' as where the class file is, regardless of where that might be (on disk, in a jar, loaded from the network - doesn't matter).
Eclipse should treat any non-java file in a 'src' directory as a file to be included verbatim in any exported jar, although you really ought to move to an actual build system sooner rather than later.
If you want to put the audio file in the 'root' (as in, it shows up in the jar as just file.mp3
, not com/foo/mobbs8player/file.mp3
) - no problem. Use .getResourceAsStream("/file.mp3")
instead (note the leading slash).
Upvotes: 2