我想尝试运行一个“用Java播放声音”的例子,但它没有用,给我一个例外! 这是JFrame类
public class JFrame {
JFrame frame = new JFrame();
}
这是SoundEffect枚举。
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();
}
}
SoundEffectDemo类。
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();
}
}
一切似乎都很正常,没有红线。但每当我试图运行它时,它就会给我这个。
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
知道如何解决这个问题吗?