在将其编译为JAR后,在Java中播放wav文件

时间:2021-07-18 15:59:29

so I am making a birthday present for a programmer friend of mine. I am not that good with code but I made a window + gif + sound. But once I test it on another PC the sound won't work anymore, but the JAR file is big enough to contain the WAV. PLease help me, I really want to make a nice birthday gift. Here is the Sound code + main

所以我正在为我的程序员朋友制作生日礼物。我对代码不是那么好,但我做了一个窗口+ gif +声音。但是一旦我在另一台PC上测试它,声音将不再起作用,但JAR文件足以包含WAV。请帮助我,我真的想做个好生日礼物。这是Sound code + main

 public static void play() {
    try {

        File file = new File("C:/Users/timma/IdeaProjects/BirthdayAshley/1" + ".wav");
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(file));
        clip.start();
        Thread.sleep(clip.getMicrosecondLength());

    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}

public static void main(String[] args){
    JFrame jf = new JFrame ("Happy Birthday");
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setSize(617,345);
    jf.add(new Birthday());
    jf.setVisible(true);
    jf.setResizable(false);
    play();

}

2 个解决方案

#1


1  

If the WAV is inside a JAR, it can't be referenced via a file. But you can open it via Class.getResourceAsStream(). Everything else should stay the same.

如果WAV在JAR中,则无法通过文件引用。但是你可以通过Class.getResourceAsStream()打开它。其他一切都应该保持不变。

InputStream stream =
    SomeClassInTheSameJar.class.getResourceAsStream("/BirthdayAshley/1.wav");

#2


0  

use <MyClass>.class().getAsStream("/1.wav") to load the file. So it will loaded from your jar not with an absolut Path that not exists.

使用 .class()。getAsStream(“/ 1.wav”)加载文件。所以它将从你的jar中加载而不是没有absolut的路径。

clip.open(AudioSystem.getAudioInputStream(<MyClass>.class.getAsStream("/1.wav")));

#1


1  

If the WAV is inside a JAR, it can't be referenced via a file. But you can open it via Class.getResourceAsStream(). Everything else should stay the same.

如果WAV在JAR中,则无法通过文件引用。但是你可以通过Class.getResourceAsStream()打开它。其他一切都应该保持不变。

InputStream stream =
    SomeClassInTheSameJar.class.getResourceAsStream("/BirthdayAshley/1.wav");

#2


0  

use <MyClass>.class().getAsStream("/1.wav") to load the file. So it will loaded from your jar not with an absolut Path that not exists.

使用 .class()。getAsStream(“/ 1.wav”)加载文件。所以它将从你的jar中加载而不是没有absolut的路径。

clip.open(AudioSystem.getAudioInputStream(<MyClass>.class.getAsStream("/1.wav")));