Playing .mp3 and .wav in Java?

前端 未结 14 2109
一整个雨季
一整个雨季 2020-11-22 06:52

How can I play an .mp3 and a .wav file in my Java application? I am using Swing. I tried looking on the internet, for something like this example:<

14条回答
  •  既然无缘
    2020-11-22 07:34

    I would recommend using the BasicPlayerAPI. It's open source, very simple and it doesn't require JavaFX. http://www.javazoom.net/jlgui/api.html

    After downloading and extracting the zip-file one should add the following jar-files to the build path of the project:

    • basicplayer3.0.jar
    • all the jars from the lib directory (inside BasicPlayer3.0)

    Here is a minimalistic usage example:

    String songName = "HungryKidsofHungary-ScatteredDiamonds.mp3";
    String pathToMp3 = System.getProperty("user.dir") +"/"+ songName;
    BasicPlayer player = new BasicPlayer();
    try {
        player.open(new URL("file:///" + pathToMp3));
        player.play();
    } catch (BasicPlayerException | MalformedURLException e) {
        e.printStackTrace();
    }
    

    Required imports:

    import java.net.MalformedURLException;
    import java.net.URL;
    import javazoom.jlgui.basicplayer.BasicPlayer;
    import javazoom.jlgui.basicplayer.BasicPlayerException;
    

    That's all you need to start playing music. The Player is starting and managing his own playback thread and provides play, pause, resume, stop and seek functionality.

    For a more advanced usage you may take a look at the jlGui Music Player. It's an open source WinAmp clone: http://www.javazoom.net/jlgui/jlgui.html

    The first class to look at would be PlayerUI (inside the package javazoom.jlgui.player.amp). It demonstrates the advanced features of the BasicPlayer pretty well.

提交回复
热议问题