Java - 不支持的音频文件异常

时间:2013-05-28 23:02:16

标签: java swing audio audio-streaming

我正在尝试为我的java游戏添加声音......

我在运行时正在玩苏丹:

static String WHOOSH = "res/WHOOSH.WAV";
static String SULTANS = "res/DireStraits_SultansOfSwing.wav";

music(SULTANS, true);

当球击中球拍时发出声音

music(WHOOSH, false);

public void music(String path, Boolean loop) {
    try {
        //will go into file folder and get music file (getResource)
        AudioInputStream audio = AudioSystem.getAudioInputStream(GamePanel.class.getResource(path));
        Clip clip = AudioSystem.getClip();
        clip.open(audio);
        clip.start();
        if (loop) {
            clip.loop(1000);
        }   
    }
    catch (Exception e) {
        System.out.println("Check: " + path + "\n");
        e.printStackTrace();
    }
}

问题:

“飞快移动”总是有效,但是苏丹的苏丹没有。 Sultans给了我这个“不支持的音频文件异常”错误,oracle docs告诉我

An UnsupportedAudioFileException is an exception indicating that an operation failed because a file did not contain valid data of a recognized file type and format.

错误:

Check: res/DireStraits_SultansOfSwing.wav

javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input URL at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)

但你可以从这些照片中看到它们都是.wav文件......

enter image description here

enter image description here

为什么会抛出这个错误?是尺寸问题吗?

谢谢!

1 个答案:

答案 0 :(得分:-1)

当我在游戏中使用wav文件时,我已经完成了这样的事情(我用你的路径更新了它):

    public void endingSound() throws IOException{

        ClassLoader cl = this.getClass().getClassLoader();
        InputStream failSound = cl.getResourceAsStream("res/DireStraits_SultansOfSwing.wav");

        if (failSound != null){

            AudioStream as = new AudioStream(failSound);         
            AudioPlayer.player.start(as);  
        }
        else{

            System.err.println("cannot load ending sound");
        }   

}

通过这种方式,我保证当你导出为jar时不会有任何问题。如果仍然无效,请尝试重命名或替换该文件;它可能会被破坏,因为@MadProgrammer说。