I have been looking for a way to export a JAR file from my project that manages to always play the sound files no matter where it is located. For this I wrote the following code that returns an exact path to the file.
public MouseHandler() {
playSound("rsc/click.wav");
}
public void playSound(final String fileName) {
File file = new File(fileName);
try {
URL fileUrl = file.toURI().toURL();
String urls = fileUrl.toString();
urls = urls.replaceFirst("file:/", "file:///");
System.out.println(urls);
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem
.getAudioInputStream(MouseHandler.class.getResourceAsStream(urls));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
When I have the AudioInputStream open the file as a stream, it throws a NullPointerException even though the URL has a value before.
file:///X:/workspace/eclipse/Minesweeper/rsc/click.wav
java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:222)
at java.desktop/javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1006)
at configs.MouseHandler.playSound(MouseHandler.java:62)
[AudioInputStream inputStream = AudioSystem
.getAudioInputStream(MouseHandler.class.getResourceAsStream(urls));]
at configs.MouseHandler.<init>(MouseHandler.java:45)
[playSound("rsc/click.wav");]
at configs.Button.<init>(Button.java:57)
at gui.Frame.<init>(Frame.java:81)
at start.Main.main(Main.java:13)
I know this doesn't happen if I give the AudioInputStream "rsc/click.wav"
, but then the file is not found when I export the project. If there is another way to export a project that can still play the audio files, I would like to use that if it works.
The solution with stackoverflow.com/tags/javasound/info worked for me, thank you very much!