AudioClip NullPointerException

236 Views Asked by At

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...

1

There are 1 best solutions below

1
On

Java is throwing a NullPointerException because clip is a null reference (it doesn't refer to an object). The code you provided looks a bit off because it's missing the new keyword that would instanciate the object.

Have you tried this?:

AudioClip clip = new AudioClip(url.toString());

Here's the documentation you should probably check out.