Java实现声音片段,NullPointerException

时间:2014-08-25 22:54:22

标签: java

嗨我正在尝试创建一个在我用方法调用时播放声音的类。但是,每当我尝试播放声音时,我都会得到一个空指针Exception。我无法弄清楚我所引用的对象但没有链接,一切对我来说都很好!

import java.applet.*;
import javax.swing.*;
import java.net.*;

public class Sound extends JApplet// Holds one audio file
{
    private AudioClip song; // Sound player
    private URL songPath; //audio path

    public Sound(String filename)
    {
        try
        {
            songPath = new URL(getCodeBase(),filename); // Get the Sound URL
            song = Applet.newAudioClip(songPath); // Load the Sound
        }
        catch(Exception e){e.printStackTrace();} // Satisfy the catch
    }
    public void playSound()
    {
        song.loop(); // Play
    }
    public void stopSound()
    {
        song.stop(); // Stop
    }
    public void playSoundOnce()
    {
        song.play(); // Play only once
    }

    public static void main(String[] args) {

        Sound s = new Sound("gameover.wav");

        s.playSoundOnce();

    }
}

1 个答案:

答案 0 :(得分:0)

import java.applet.*;
import javax.swing.*;
import java.net.*;

public class Sound extends JApplet// Holds one audio file
{
    private AudioClip song; // Sound player
    private URL songPath; //audio path

    public Sound(String filename)
    {
        try
        {
            songPath = new URL(getCodeBase(),filename); [1]
            song = Applet.newAudioClip(songPath); 
        }
        catch(Exception e){e.printStackTrace();} // Satisfy the catch
    }
    public void playSound()
    {
        song.loop(); [2]
    }
    public void stopSound()
    {
        song.stop(); [2]
    }
    public void playSoundOnce()
    {
        song.play(); [2]
    }

    public static void main(String[] args) {

        Sound s = new Sound("gameover.wav");

        s.playSoundOnce();

    }
}

空指针可以是

的可能位置
  1. 如果getCodeBase()抛出NPE
  2. 如果由于某种原因没有初始化歌曲(#1中引发了异常),那么你试图在空对象上调用方法
  3. 我打赌你在#1遇到问题,然后你的歌曲对象没有被创建,然后你因为#2而每次尝试播放它时都会获得NPE。

    最有可能的情况是,您的applet无法访问songPath,可能是因为路径错误或者您的applet需要权限to access the file outside its sandbox