在Java上播放声音时的NullPointer

时间:2012-06-12 16:49:22

标签: java nullpointerexception javasound

尝试播放声音时出错。由于某种原因,我得到一个空指针异常。我正在使用的位置和文件都是exsist,当输出文件字符串时,我确实获得了文件的正确路径。 nullpointer位于.open行。我做错了什么?

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();
    }

}

这是错误(第一行是位置):

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)

1 个答案:

答案 0 :(得分:4)

Class.getResource()不接受文件名 - 它需要资源名称。

为什么不直接创建File并将其传递给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));