I wanted to try to run one example of "Playing sound in Java" but its not working, throwing me an Exception! This is The JFrame Class
public class JFrame {
JFrame frame = new JFrame();
}
Here is the SoundEffect enum.
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public enum SoundEffect {
SONG("Sound.wav");
public static enum Volume {
MUTE, LOW, MEDIUM, HIGH
}
public static Volume volume = Volume.LOW;
private Clip clip;
SoundEffect(String SONG) {
try {
URL url = this.getClass().getClassLoader().getResource(SONG);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);
clip = AudioSystem.getClip();
clip.open(audioInputStream);
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public void play() {
if (volume != Volume.MUTE) {
if (clip.isRunning())
clip.stop();
clip.setFramePosition(0);
clip.start();
}
}
static void init() {
values();
}
}
The SoundEffectDemo class.
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SoundEffectDemo extends JFrame {
public SoundEffectDemo(){
SoundEffect.init();
SoundEffect.volume = SoundEffect.Volume.LOW;
Container cp = this.getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
JButton btnSound1 = new JButton("Sound 1");
btnSound1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SoundEffect.SONG.play();
}
});
cp.add(btnSound1);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Test SoundEffct");
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new SoundEffectDemo();
}
}
Everything seems to be normal, there are no red lines. But whenever i try to run it, its giving me that.
Exception in thread "main" java.lang.ExceptionInInitializerError
at SoundEffectDemo.<init>(SoundEffectDemo.java:12)
at SoundEffectDemo.main(SoundEffectDemo.java:30)
Caused by: java.lang.NullPointerException
at com.sun.media.sound.StandardMidiFileReader.getSequence(Unknown Source)
at javax.sound.midi.MidiSystem.getSequence(Unknown Source)
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at SoundEffect.<init>(SoundEffect.java:20)
at SoundEffect.<clinit>(SoundEffect.java:11)
... 2 more
Any idea how to fix that?