如何播放Jar文件中resources文件夹中的MP3文件?

时间:2019-12-19 19:29:01

标签: java jar stream mp3 executable-jar

我正在尝试访问jar文件中resources文件夹内的MP3文件。我遇到了一些问题,无法阅读。

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;

import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;

public class MP3 {

    private static final Logger logger = Logger.getLogger(Main.class.getName());


    private BasicPlayer player;


    /**
     * Constructor
     */
    public MP3() {
        player = new BasicPlayer();
    }

    public void changeSong(song) {

        // Change song now
        String pathToMp3 = System.getProperty("user.dir") + this.getClass().getResource(song);
        try {
            player.open(new URL("file:///" + pathToMp3));
            player.play();
            logger.info("Playing the song: " + song);
        } catch (MalformedURLException | BasicPlayerException e) {
            logger.info("Could not turn on MP3 music from: " + pathToMp3);
        }

    }

}

pathToMp3如下所示: enter image description here

我已经解决了CSV读取的类似问题。而不是从资源中读取。我将资源阅读为流。

InputStream in = getClass().getResourceAsStream("/file.txt"); 
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

但是这里的问题是

layer.open(new URL("file:///" + pathToMp3));

采用参数URL,而不是流或字符串。您知道如何从可执行JAR文件内的resources文件夹中流式传输MP3:s吗?

更新

       // Change song now
        String pathToMp3 = getClass().getResource(song).toString();
        InputStream in = getClass().getResourceAsStream(song);
        try {
            player.open(in);
            player.play();
            logger.info("Playing the song: " + song);
        } catch (BasicPlayerException e) {
            logger.info("Could not turn on MP3 music from: " + pathToMp3);
        }

给出错误:

enter image description here

1 个答案:

答案 0 :(得分:0)

我从here复制了BasicPlayerTest示例,并修改了play方法以采用URL

然后运行项目中的主要作品,并在jar中导出之后。

请注意,我已将resources文件夹复制到src文件夹中。

public static void main(String[] args) {
    BasicPlayerTest test = new BasicPlayerTest();
    test.play(test.getClass().getResource("/resources/test.mp3")); 
}

我在日志中看到的网址是:
jar:file:/C:/Temp/mp3.jar!/resources/test.mp3