Url problems with jar



我的音频文件路径有问题。

当我编译项目的音频听起来很好,但当我打开jar它给了我这个错误(我理解的错误,但我看不出我做错了什么…):

如果是西班牙语"No existe el archivo o el directorio"意思是"不存在这样的文件或目录"

/home/user1 NetBeansProjects project1/dist/project1.jar !/音乐/2. wavjava.lang.IllegalStateException: java.io.FileNotFoundException:/home/user1/netbeansprojects/project1/dist/project1.jar!/music/2.wav(不存在el目录的文件)logic.AudioFilePlayer.run (AudioFilePlayer.java: 54)原因:java.io.FileNotFoundException:/home/user1/netbeansprojects/project1/dist/project1.jar!/music/2.wav(不存在el目录的el档案)在java.io.FileInputStream。打开(本机方法)在java.io.FileInputStream。(FileInputStream.java: 146)com.sun.media.sound.WaveFloatFileReader.getAudioInputStream (WaveFloatFileReader.java: 164)javax.sound.sampled.AudioSystem.getAudioInputStream (AudioSystem.java: 1179)logic.AudioFilePlayer.run (AudioFilePlayer.java: 36)

代码如下:

boolean loop = true;
private final URL url = getClass().getResource("/music/2.wav");
private final String convertFilePath = url.toString();
String filePath = convertFilePath.substring(convertFilePath.lastIndexOf("file:") + 5);
@Override
public void run() {
    while (loop == true) {
        final File file = new File(filePath);
        System.out.println(filePath);
        try (final AudioInputStream in = getAudioInputStream(file)) {
            final AudioFormat outFormat = getOutFormat(in.getFormat());
            final Info info = new Info(SourceDataLine.class, outFormat);
            try (final SourceDataLine line
                    = (SourceDataLine) AudioSystem.getLine(info)) {
                if (line != null) {
                    line.open(outFormat);
                    line.start();
                    stream(getAudioInputStream(outFormat, in), line);
                    line.drain();
                    line.stop();
                }
            }
        } catch (UnsupportedAudioFileException | LineUnavailableException | IOException e) {
            throw new IllegalStateException(e);
        }
    }
}
private AudioFormat getOutFormat(AudioFormat inFormat) {
    final int ch = inFormat.getChannels();
    final float rate = inFormat.getSampleRate();
    return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
}
private void stream(AudioInputStream in, SourceDataLine line)
        throws IOException {
    final byte[] buffer = new byte[4096];
    for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
        line.write(buffer, 0, n);
    }
}

使用JAR时,您应该处理jar:file URL,而不是操纵它并尝试自己创建File对象。你应该把你从getResource得到的URL直接传递给构造函数,如果它支持的话。

// get the URL of the file as usual
URL url = getClass().getResource("/music/2.wav");
// get stream directly from URL, which could be a file or a jar:file
AudioInputStream in = getAudioInputStream(url);

如果这不起作用,并且您的库可以接受输入流,您可以尝试使用ClassLoader#getResourceAsStream并将其传递给适当的构造函数/方法。

否则,您可以尝试将文件提取到本地某个地方,然后传递该文件的路径。

我的猜测是,当给定URL(使用jar:file协议)时,一些库根本不支持从JAR加载文件。

最新更新