0

none of the answers I found to this question worked, so I have to ask here: I'm using Eclipse and I have a program that I export as a runnable jar, and it plays an audio, but the audio has to be in the same folder as the exported jar file or else it doesn't play. How can I package it into the runnable jar so that it doesn't need the audio to actually be there? PS: I'm doing things the old-fashioned way so not using a build system (Maven or Gradle) this is my code; it plays an audio file when a button is pressed:

    AudioFormat audioformat = null;
                DataLine.Info info = new DataLine.Info(Clip.class, audioformat);
                try {
                    Clip audioclip = (Clip) AudioSystem.getLine(info);
                    File audio1 = new File("audiofile.wav");
                    
                    AudioInputStream audiostream = AudioSystem.getAudioInputStream(audio1); 
                    
                    audioformat = audiostream.getFormat();
                    audioclip.open(audiostream);
                    audioclip.start();
                    audiostream.close();
                } catch (LineUnavailableException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (UnsupportedAudioFileException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } 
```
4

1 回答 1

2

使用getResourceAsStream

class Example {
    void getAudioData() {
        try (InputStream in = Example.class.getResourceAsStream("file.mp3")) {
            // pass 'in' to your music player of choice.
            // NB: If you can only pass 'File' or 'Path' objects, and not
            // URL or InputStream objects, get another music playing library.
        }
    }

    void alternateForm() {
        musicPlayer.play(Example.class.getResource("file.mp3"));
        // Use this form if your music player takes URLs and not InputStreams.
    }
}

你的罐子最终看起来像这样:

jar tvf Mobbs8app.jar
1234 Wed 19 Jan 20:00 com/foo/mobbs8/Main.class
1234 Wed 19 Jan 20:00 com/foo/mobbs8/Example.class
1234 Wed 19 Jan 20:00 com/foo/mobbs8/file.mp3

这是你Main.class的主类,包头“package com.foo.mobbs8;” -getResourceAsStream在与类文件所在位置相同的“目录”中查找,无论它可能在哪里(在磁盘上,在 jar 中,从网络加载 - 没关系)。

Eclipse 应该将 'src' 目录中的任何非 java 文件视为要逐字包含在任何导出的 jar 中的文件,尽管您确实应该尽早而不是稍后迁移到实际的构建系统。

如果您想将音频文件放在“根”中(如,它在 jar 中显示为 just file.mp3, not com/foo/mobbs8player/file.mp3) - 没问题。改为使用.getResourceAsStream("/file.mp3")(注意前导斜杠)。

于 2020-07-07T21:33:20.827 回答