简体   繁体   中英

How to play MP3 files that are in the resources folder in a Jar file?

I'm trying to access the MP3 files that are located inside the resources folder insidea jar file. I got some issues, they can't be readed.

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);
        }

    }

}

The pathToMp3 looks like this: 在此处输入图片说明

I have solved a similar issue with CSV read. Instead of reading from resources. I read the resources as streams.

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

But the problem here is that

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

Takes the argument URL, not stream or string. Do you know how to stream MP3:s from the resources folder inside a executable JAR file?

Update:

       // 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);
        }

Gives the error:

在此处输入图片说明

I copied the BasicPlayerTest example from here and modified the play method to take an URL .

Then running the main works from the project and after the export in the jar.

Note that I copied the resources folder inside the src folder.

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

The url I am seeing in the log is:
jar:file:/C:/Temp/mp3.jar!/resources/test.mp3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM