1

对在 Mac 上的 Eclipse 上运行的 javax.sound.sampled.Clip NullPointerException 感到困惑。输入波形文件存在,构造函数工作正常。对象实例被创建。只是无法访问实例方法,其中任何一个。这里可能是 Java 101 问题,所以我提前道歉,如果是这样?或者 Eclipses 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();
    }

}

4

1 回答 1

0

这是因为在以下行中:

 Clip myClip = AudioSystem.getClip();

您声明并初始化局部变量,并且 myClip 字段保持为空。尝试将上面的行替换为

 myClip = AudioSystem.getClip();
于 2014-04-06T15:50:10.813 回答