使用javax.sound.sampled.Clip NullPointerException神秘化

时间:2014-04-06 15:25:23

标签: nullpointerexception javax.sound.sampled

使用javax.sound.sampled.Clip NullPointerException神秘化 在Mac上运行Eclipse。 输入波形文件存在, 构造函数工作正常。对象实例已创建。 只是无法访问实例方法,其中任何一个。 可能是这里的Java 101问题,所以我提前道歉,如果是的话? 或者日食101,就此而言......

public class AudioClipTester {

public static void main(String[] args) 
{
    // TODO Auto-generated method stub

    AudioClipPlayer mooMoo = new AudioClipPlayer("cow.wav");
    mooMoo.play();
}
}

/ =====

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 * Handles play, pause, and looping of sounds for the game.
 * @author Tyler Thomas
 *
 */
public class AudioClipPlayer 
{
    private Clip myClip;
    public AudioClipPlayer(String fileName) {
            try {
                File file = new File(fileName);
                if (file.exists()) {
                    Clip myClip = AudioSystem.getClip();
                    System.out.println("file "+fileName+" is in root dir");
                    AudioInputStream ais = AudioSystem.getAudioInputStream(file.toURI().toURL());
                    myClip.open(ais);
                    System.out.println("ais "+ais.toString()+" is open");
                    }
                else {
                    throw new RuntimeException("Sound: file not found: " + fileName);
                }
            }
            catch (MalformedURLException e) {
                throw new RuntimeException("Sound: Malformed URL: " + e);
            }
            catch (UnsupportedAudioFileException e) {
                throw new RuntimeException("Sound: Unsupported Audio File: " + e);
            }
            catch (IOException e) {
                throw new RuntimeException("Sound: Input/Output Error: " + e);
            }
            catch (LineUnavailableException e) {
                throw new RuntimeException("Sound: Line Unavailable: " + e);
            }
    }
    public void play(){
        System.out.println("clip "+myClip.toString()+" is about to play");
        myClip.setFramePosition(0);  // Must always rewind!
        myClip.loop(0);
        myClip.start();
 //           Thread.sleep(10000);  

    }
    public void loop(){
        myClip.loop(Clip.LOOP_CONTINUOUSLY);
    }
    public void stop(){
        myClip.stop();
    }

}

1 个答案:

答案 0 :(得分:0)

这是因为在以下行中:

 Clip myClip = AudioSystem.getClip();

声明并初始化局部变量,字段myClip保持为null。尝试用

替换上面的行
 myClip = AudioSystem.getClip();