0

我一直在寻找一种从我的项目中导出 JAR 文件的方法,无论它位于何处,它都能始终播放声音文件。为此,我编写了以下代码,该代码返回文件的确切路径。

public MouseHandler() {
    playSound("rsc/click.wav");
}
public void playSound(final String fileName) {
    File file = new File(fileName);
    try {
        URL fileUrl = file.toURI().toURL();
        String urls = fileUrl.toString();
        urls = urls.replaceFirst("file:/", "file:///");
        System.out.println(urls);
        Clip clip = AudioSystem.getClip();
        AudioInputStream inputStream = AudioSystem
                .getAudioInputStream(MouseHandler.class.getResourceAsStream(urls));
        clip.open(inputStream);
        clip.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

当我让 AudioInputStream 将文件作为流打开时,即使 URL 之前有一个值,它也会引发 NullPointerException。

file:///X:/workspace/eclipse/Minesweeper/rsc/click.wav
java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:222)
at java.desktop/javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1006)
at configs.MouseHandler.playSound(MouseHandler.java:62)
[AudioInputStream inputStream = AudioSystem
                .getAudioInputStream(MouseHandler.class.getResourceAsStream(urls));]
at configs.MouseHandler.<init>(MouseHandler.java:45)
[playSound("rsc/click.wav");]
at configs.Button.<init>(Button.java:57)
at gui.Frame.<init>(Frame.java:81)
at start.Main.main(Main.java:13)

我知道如果我提供 AudioInputStream 就不会发生这种情况"rsc/click.wav",但是当我导出项目时找不到该文件。如果有另一种方法可以导出仍然可以播放音频文件的项目,如果它有效,我想使用它。

4

1 回答 1

0

stackoverflow.com/tags/javasound/info 的解决方案对我有用,非常感谢!

public void playSound(final URL fileName) throws Exception {

        new Thread(new Runnable() {
        public void run() {
            try {
                AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(fileName);
                AudioFormat audioFormat = new AudioFormat(Encoding.PCM_SIGNED, 44100, 16, 2, 4, 44100, false);
                Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
                SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
                sourceDataLine.open(audioFormat);
                int bytesRead = 0;
                byte[] buffer = new byte[1024];
                sourceDataLine.start();
                while ((bytesRead = audioInputStream.read(buffer)) != -1) {
                    sourceDataLine.write(buffer, 0, bytesRead);
                }
                sourceDataLine.drain();
                sourceDataLine.stop();
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
        }
    }).start();
}
于 2021-04-19T08:24:04.767 回答