Playing .mp3 and .wav in Java?

2018-12-31 06:03发布

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:

public void playSound() {
    try {
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("D:/MusicPlayer/fml.mp3").getAbsoluteFile());
        Clip clip = AudioSystem.getClip();
        clip.open(audioInputStream);
        clip.start();
    } catch(Exception ex) {
        System.out.println("Error with playing sound.");
        ex.printStackTrace();
    }
}

But, this will only play .wav files.

The same with:

http://www.javaworld.com/javaworld/javatips/jw-javatip24.html

I want to be able to play both .mp3 files and .wav files with the same method.

标签: java audio mp3 wav
12条回答
呛了眼睛熬了心
2楼-- · 2018-12-31 06:55

To add MP3 reading support to Java Sound, add the mp3plugin.jar of the JMF to the run-time class path of the application.

Note that the Clip class has memory limitations that make it unsuitable for more than a few seconds of high quality sound.

查看更多
孤独寂梦人
3楼-- · 2018-12-31 06:57

The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29

Here is the code for the class

public class SimplePlayer {

    public SimplePlayer(){

        try{

             FileInputStream fis = new FileInputStream("File location.");
             Player playMP3 = new Player(fis);

             playMP3.play();

        }  catch(Exception e){
             System.out.println(e);
           }
    } 
}

and here are the imports

import javazoom.jl.player.*;
import java.io.FileInputStream;
查看更多
无色无味的生活
4楼-- · 2018-12-31 06:59

It's been a while since I used it, but JavaLayer is great for MP3 playback

查看更多
永恒的永恒
5楼-- · 2018-12-31 06:59

Do a search of freshmeat.net for JAVE (stands for Java Audio Video Encoder) Library (link here). It's a library for these kinds of things. I don't know if Java has a native mp3 function.

You will probably need to wrap the mp3 function and the wav function together, using inheritance and a simple wrapper function, if you want one method to run both types of files.

查看更多
谁念西风独自凉
6楼-- · 2018-12-31 07:05

You need to install JMF first (download using this link)

File f = new File("D:/Songs/preview.mp3");
MediaLocator ml = new MediaLocator(f.toURL());
Player p = Manager.createPlayer(ml);
p.start();

don't forget to add JMF jar files

查看更多
旧人旧事旧时光
7楼-- · 2018-12-31 07:08

Use this library: import sun.audio.*;

public void Sound(String Path){
    try{
        InputStream in = new FileInputStream(new File(Path));
        AudioStream audios = new AudioStream(in);
        AudioPlayer.player.start(audios);
    }
    catch(Exception e){}
}
查看更多
登录 后发表回答