0

尝试播放声音时出现错误。由于某种原因,我得到了一个空指针异常。我使用的位置和文件都存在,并且在输出文件字符串时,我确实得到了文件的正确路径。空指针位于 .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)
4

1 回答 1

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));
于 2012-06-12T16:51:16.877 回答