Search code examples
javamp3

Playing an external mp3 with java 8


I know this subject has tons of answers and duplicates, and trust me, I spent hours trying each one that was even remotely related to what I'm trying to do.

I would like to be able to play a mp3 in a specific folder on my computer with my program using its relative path;

It sounds easy at first, but then, from one tuto to another I downloaded stuff I'm unable to use: jmf and mfSampledSP for example (it's easy they say, download and add the jar to your project...... and now what?) or I read I should look into some links (with hundreds of lines each which explain not much to nothing at all). promising Youtube tutorials that supposedly teach you how to do it 147 simple (and/or deprecated) steps on a 45mn video, I ran away when they tried to make me change my environment variables.

So I'm asking once more, for all those who might be struggling like I am currently: How do we play external mp3s in a java program?

That can't be requiring a java master degree right?

Thanks in advance and I apologise if noobs like me feel annoying to you guys.


Solution

  • The JLayer library (http://www.javazoom.net/javalayer/javalayer.html) should do what you want, and has a simple interface.

    Put the jar (jl1.0.1.jar) in your classpath, and then use something like this to play a file:

    try (FileInputStream fis = new FileInputStream(mp3FileName))
    {
        Player player = new Player(fis);
        player.play();
    } catch (IOException | JavaLayerException e) {
        e.printStackTrace();
    }
    

    Note that player.play() won't return until the mp3 has finished playing; if you want to do something else in the mean time, run it in a separate thread.