简体   繁体   English

如何播放声音而不出现异常?

[英]How would play sound and not get an Exception?

I've got this class for playing sound but every time I try to use it I get a null pointer exception. 我有用于播放声音的此类,但是每次尝试使用它时,都会得到一个空指针异常。 This is how I'm using it: 这就是我的使用方式:

import javax.sound.sampled.*;

public class Sound {

public Clip play(String filename) {
    Clip clip = null;

    try {
        AudioInputStream audioIn = AudioSystem.getAudioInputStream(getClass().getResource(filename));
        clip = AudioSystem.getClip();
        clip.open(audioIn);
        clip.start();
    } catch (Exception e) { e.printStackTrace(); }

    return clip;
    }

}

public Sound sound; 
sound.play("PathToFile");

Try: 尝试:

File file = new File(filename);
this.getClass().getClassLoader().getResource(file.getPath());

Did you initialize the sound variable? 您是否初始化了声音变量? You should do something like: 您应该执行以下操作:

Sound sound = new Sound(); //Notice the 'new' keyword here
sound.play("PathToFile");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM