简体   繁体   中英

NullPointer when playing sound on Java

I'm getting an error when trying to play sound. I'm getting a null pointer exception for some reason. The location and file I'm using both exsist, and when outputting the file string I do get the correct path to the file. The nullpointer is on the .open line. What am I doing wrong?

package main;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Sound {
    Clip background;

    public void init() {

    try {
        String file = new File("").getAbsolutePath() + "\\Sounds\\Pacman_Opening.wav";
        System.out.println(file);
        background = AudioSystem.getClip();
        background.open(AudioSystem.getAudioInputStream(getClass().getResource(file)));
    } catch (LineUnavailableException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedAudioFileException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

    public void playBG() {
        background.start();
    }
    public void stopBG() {
        background.stop();
    }   
    public static void main(String[] args) {
        Sound s = new Sound();
        s.init();
        s.playBG();
    }

}

This is the error (the first line is the location):

Exception in thread "main" java.lang.NullPointerException
    at com.sun.media.sound.WaveFileReader.getAudioInputStream(Unknown Source)
    at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
    at main.Sound.init(Sound.java:21)
    at main.Sound.main(Sound.java:42)

Class.getResource() doesn't take a filename - it takes a resource name.

Why don't you just create a File instead and pass that to getAudioInputStream ?

// TODO: Avoid backslashes in file constructor calls; there are other ways
// of creating relative paths
File file = new File("Sounds\\Pacman_Opening.wav");
...
background.open(AudioSystem.getAudioInputStream(file));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM