So I'm learning how to use audio clips and so far my program is supposed to play a sound after a button is clicked but before any of that, i get a nullpointexception on my AudioClip.
public class soundtest extends JFrame implements ActionListener {
URL url = this.getClass().getResource("/Sounds/gameover.wav");
AudioClip clip = Applet.newAudioClip(url);
JButton button = new JButton("Play");
public soundtest() {
super("Swing Window");
setSize(500, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
button.addActionListener(this);
add(button);
setVisible(true);
}
public static void main(String[] args) {
new soundtest();
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == button) {
clip.play();
}
}
}
I've even tried other peoples codes and I still get an error.
My audio file is definitely in the correct place...
Java is throwing a
NullPointerException
becauseclip
is anull
reference (it doesn't refer to an object). The code you provided looks a bit off because it's missing thenew
keyword that would instanciate the object.Have you tried this?:
Here's the documentation you should probably check out.