簡體   English   中英

在Java上播放聲音時為NullPointer

[英]NullPointer when playing sound on Java

嘗試播放聲音時出現錯誤。 由於某種原因,我收到了空指針異常。 我同時使用的位置和文件都存在,並且在輸出文件字符串時,我確實獲得了文件的正確路徑。 空指針位於.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)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM