I want to play a .wav file using java code which is in a jar file as resource. My code is look like this -
try {
URL defaultSound = getClass().getResou
The following allows me to play a sound in Eclipse project and an exported jar file:
- note the BufferedInputStream is used
- Note, inputStream is used instead of file.
In my main():
playAlarmSound();
in my class:
public static void playAlarmSound() {
ClassLoader classLoader = App.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("alarmsound.wav");
try {
Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(new BufferedInputStream(inputStream));
clip.open(ais);
clip.start();
} catch (IOException | LineUnavailableException | UnsupportedAudioFileException e) {
System.err.println("ERROR: Playing sound has failed");
e.printStackTrace();
}
}