我正在为我的游戏制作一个声音类,在尝试和尝试后我似乎无法摆脱NullPointerException。发生这种情况是因为我无法访问try / catch语句中的变量。
以下是代码:
package util;
import java.applet.*;
import java.net.URL;
public class Sound
{
private AudioClip audio;
private URL file;
public Sound(String srcfile)
{
try
{
this.file = new URL(srcfile);
}
catch(Exception e){}
this.audio = Applet.newAudioClip(file);
}
public void Play()
{
this.audio.play();
}
public void Loop()
{
this.audio.loop();
}
public void Stop()
{
this.audio.stop();
}
public AudioClip getAudio()
{
return audio;
}
public void setAudio(AudioClip audio)
{
this.audio = audio;
}
}
这是错误(不再获取):
Exception in thread "main" java.lang.NullPointerException
at sun.applet.AppletAudioClip.<init>(Unknown Source)
at java.applet.Applet.newAudioClip(Unknown Source)
at util.Sound.<init>(Sound.java:19)
at main.Blocks.run(Blocks.java:38)
at main.Blocks.main(Blocks.java:26)
修改旧代码后,她就是新代码:
package util;
import java.applet.*;
import java.net.URL;
public class Sound
{
private AudioClip audio;
public Sound(String srcfile)
{
try
{
this.audio = Applet.newAudioClip(new URL("file://" + srcfile));
}
catch(Exception e)
{
Log.log(e.getMessage(), Log.ERROR);
e.printStackTrace();
System.exit(1);
}
}
public void Play()
{
this.audio.play();
}
public void Loop()
{
this.audio.loop();
}
public void Stop()
{
this.audio.stop();
}
public AudioClip getAudio()
{
return audio;
}
public void setAudio(AudioClip audio)
{
this.audio = audio;
}
}
我在打电话 玩(); 但是没有发生的事情
以下是我调用方法的方法:
Sound snd = new Sound("res/dev/sound.wav");
snd.Play();
任何帮助都将不胜感激。
答案 0 :(得分:2)
从您的类的设计方式看起来并不像file
变量存在于构造函数之外。这样的事情可能会很好:
public Sound(String srcfile) {
try {
this.audio = Applet.newAudioClip(new URL(srcfile));
}
catch(Exception e){
//at least print the stack trace
e.printStackTrace();
//do some proper exception handling that makes sense for you app!
}
}