Search code examples
javajarmp3classpathembedded-resource

how to get classpath from mp3 within a jar file


I've got a problem with my classpath within a jar file. With pictures
getClass().getResource("picture.png") works fine. But I need to get a mp3 file.
If I put in the whole path outside of the jar file it works just fine, however if i try it
without the full path like getClass().getResource("picture.png") it says "File not Found". So I'm looking for a solution for the path of song.mp3 so that if I build the .jar and open it on a different computer the song still plays.

this is my code:

package bgmusic;

import java.io.*;

import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.PlugInManager;
import javax.media.format.AudioFormat;

public class Bgmusic {
    public static void main(String[] args) {
        Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
        Format input2 = new AudioFormat(AudioFormat.MPEG);
        Format output = new AudioFormat(AudioFormat.LINEAR);
        PlugInManager.addPlugIn(
            "com.sun.media.codec.audio.mp3.JavaDecoder",
            new Format[]{input1, input2},
            new Format[]{output},
            PlugInManager.CODEC
        );
        try{
            Player player = Manager.createPlayer(new MediaLocator(new File("song.mp3").toURI().toURL()));
            player.start();
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

Solution

  • If the file is inside of your jar, you can not use new File("song.mp3");. The file expects it to be inside of your normal os path, which it's not.

    To get files from within your jar you need to use getResource

    Example, assuming song.mp3 is in the root of your jar file and not in a directory:

    URL url = this.getClass().getResource("song.mp3"); 
    

    From within a static method you should be able to get it as follows

    URL url = BgMusic.class.getResource("song.mp3");