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
Perfect Solution.......
URL url = this.getClass().getResource("sounds/beep.au");
String urls=url.toString();
urls=urls.replaceFirst("file:/", "file:///");
AudioClip ac=Applet.newAudioClip(new URL(urls));
ac.play();
try {
AudioPlayer.player.start(new AudioStream(getClass().getResourceAsStream("/sound/SystemNotification.wav")));
} catch (Exception e) {
e.printStackTrace();
}
Use Class.getResourceAsStream()
Once you have a handle to the inputStream, get the audioInputStream and do the rest.
InputStream is = getClass().getResourceAsStream("......");
AudioInputStream ais = AudioSystem.getAudioInputStream(is);
Clip clip = AudioSystem.getClip();
clip.open(ais);
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();
}
}
Please refer to my previous answer at making a single-jar java application . The title is misleading, but the poster was trying to do something almost identical to you. Some of the best details are in the link to the chat log.
Have you tried:
InputStream is= getClass().getResourceAsStream("/images/ads/WindowsNavigationStart.wav");
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(is);
Essentially I do not think you can create a File out of a URI in the jar file. But you can pass the input stream directly.