I am creating a software for personal use titled BatteryBeeper. It will remind me to charge the laptop when the charge is whatever I set to be reminded at.
It is supposed to play a sound when the charge hits the set threshold.
I had a look at the answer: sound not playing in jar and my AudioInputStream
is constructed similar to what Jigar Joshi mentioned.
However I get a null exception:
java.lang.NullPointerException
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at demo.BatteryBeeper.setupSoundPlayback(BatteryBeeper.java:169)
at demo.BatteryBeeper.<init>(BatteryBeeper.java:41)
at demo.BatteryBeeper.main(BatteryBeeper.java:35)
Here is my code to load the sound:
public void setupSoundPlayback(){
try{
buzzer = AudioSystem.getClip();
in = AudioSystem.getAudioInputStream(BatteryBeeper.class.
getResourceAsStream("sound/buzzer3_x.wav"));
buzzer.open(in);
}catch(Exception e){
e.printStackTrace();
}
}
Here is the code to play it:
public void playSound(){
buzzer.start();
}
What is causing the problem ?
This is a usual Eclipse project. There is a sound
folder under src
which has the wave file
After AlexR's answer, I changed the path and got a new exception:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input stream
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at demo.BatteryBeeper.setupSoundPlayback(BatteryBeeper.java:169)
at demo.BatteryBeeper.<init>(BatteryBeeper.java:41)
at demo.BatteryBeeper.main(BatteryBeeper.java:35)
You problem is not in playing the sound. Your problem is in access to embedded resource. When you are using BatteryBeeper.class.getResourceAsStream("sound/buzzer3_x.wav")
you try to retrieve resource located in same package where class BatteryBeeper
is. This means that your file is in /demo/sound/buzzer3_x.wav
. It seems this is wrong. If your file really is in sound/buzzer3_x.wav
use getResourceAsStream("/sound/buzzer3_x.wav")
(pay attention on the leading slash in the path).