0

我正在尝试为我的 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 文档告诉我

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文件......

在此处输入图像描述

在此处输入图像描述

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

谢谢!

4

1 回答 1

-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 所说,它可能已损坏。

于 2013-05-29T00:13:25.717 回答