Use JLayer to play mp3 resource

1.2k views Asked by At

I am trying to use JLayer to play an mp3. The file is in my jar, but I can't figure out how to make it play. How would I give my app the path of the mp3 file in the same package as my classes? Here is my code:

File file = new File("audio.mp3");

System.out.println("located media at "+file.getAbsolutePath());

AdvancedPlayer player = null;

try {

    player = new AdvancedPlayer(new FileInputStream(file), 

    FactoryRegistry.systemRegistry().createAudioDevice());
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (JavaLayerException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println("Starting the music... ");
try {
    player.play();
} catch (JavaLayerException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
2

There are 2 answers

0
mysticfyst On

Why don't you try absolute path to play the song. Use this code for reference:

FileInputStream fis = new FileInputStream("G:\\Songs\\fireinthehole.mp3");
player = new AdvancedPlayer(fis);
player.play();

Note the use of double '\' in the path.

0
Zhao Yun On

You should not use File for resources in the source folders.
Try
InputStream is = getClass().getResourceAsStream("/(package name)/audio.mp3");