在Java中播放.mp3和.wav?

时间:2011-05-18 13:21:07

标签: java audio mp3 wav

如何在Java应用程序中播放.mp3.wav文件?我正在使用Swing。我尝试在互联网上寻找类似这样的例子:

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();
    }
}

但是,这只会播放.wav个文件。

同样的:

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

我希望能够使用相同的方法播放.mp3个文件和.wav个文件。

15 个答案:

答案 0 :(得分:110)

Java FX有MediaMediaPlayer个类,它们将播放mp3文件。

示例代码:

String bip = "bip.mp3";
Media hit = new Media(new File(bip).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();

您需要以下导入语句:

import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

答案 1 :(得分:30)

我写了一个纯java的mp3播放器:mp3transform

答案 2 :(得分:18)

你只能使用java API播放.wav:

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

代码:

AudioInputStream audioIn = AudioSystem.getAudioInputStream(MyClazz.class.getResource("music.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();

用jLayer播放.mp3

答案 3 :(得分:15)

我使用它已经有一段时间了,但JavaLayer非常适合MP3播放

答案 4 :(得分:12)

使用标准的javax.sound API,一个Maven依赖,完全开源( Java 7 需要):

的pom.xml

 <!-- 
    We have to explicitly instruct Maven to use tritonus-share 0.3.7-2 
    and NOT 0.3.7-1, otherwise vorbisspi won't work.
   -->
<dependency>
  <groupId>com.googlecode.soundlibs</groupId>
  <artifactId>tritonus-share</artifactId>
  <version>0.3.7-2</version>
</dependency>
<dependency>
  <groupId>com.googlecode.soundlibs</groupId>
  <artifactId>mp3spi</artifactId>
  <version>1.9.5-1</version>
</dependency>
<dependency>
  <groupId>com.googlecode.soundlibs</groupId>
  <artifactId>vorbisspi</artifactId>
  <version>1.0.3-1</version>
</dependency>

代码

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

import static javax.sound.sampled.AudioSystem.getAudioInputStream;
import static javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED;

public class AudioFilePlayer {

    public static void main(String[] args) {
        final AudioFilePlayer player = new AudioFilePlayer ();
        player.play("something.mp3");
        player.play("something.ogg");
    }

    public void play(String filePath) {
        final File file = new File(filePath);

        try (final AudioInputStream in = getAudioInputStream(file)) {

            final AudioFormat outFormat = getOutFormat(in.getFormat());
            final Info info = new Info(SourceDataLine.class, outFormat);

            try (final SourceDataLine line =
                     (SourceDataLine) AudioSystem.getLine(info)) {

                if (line != null) {
                    line.open(outFormat);
                    line.start();
                    stream(getAudioInputStream(outFormat, in), line);
                    line.drain();
                    line.stop();
                }
            }

        } catch (UnsupportedAudioFileException 
               | LineUnavailableException 
               | IOException e) {
            throw new IllegalStateException(e);
        }
    }

    private AudioFormat getOutFormat(AudioFormat inFormat) {
        final int ch = inFormat.getChannels();

        final float rate = inFormat.getSampleRate();
        return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
    }

    private void stream(AudioInputStream in, SourceDataLine line) 
        throws IOException {
        final byte[] buffer = new byte[4096];
        for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
            line.write(buffer, 0, n);
        }
    }
}

参考文献:

答案 5 :(得分:12)

我建议使用BasicPlayerAPI。它是开源的,非常简单,不需要JavaFX。 http://www.javazoom.net/jlgui/api.html

下载并解压缩zip文件后,应将以下jar文件添加到项目的构建路径中:

  • basicplayer3.0.jar
  • 所有来自 lib 目录的jar(在BasicPlayer3.0内)

这是一个简约的用法示例:

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();
}

必需的导入:

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

这就是你开始播放音乐所需要的一切。播放器正在启动和管理自己的播放线程,并提供播放,暂停,恢复,停止搜索功能。

有关更高级的用法,您可以查看jlGui音乐播放器。它是一个开源的WinAmp克隆:http://www.javazoom.net/jlgui/jlgui.html

要查看的第一个类是 PlayerUI (在包javazoom.jlgui.player.amp中)。 它很好地演示了BasicPlayer的高级功能。

答案 6 :(得分:4)

我发现最简单的方法是从http://www.javazoom.net/javalayer/sources.html下载JLayer jar文件并将其添加到Jar库http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29

这是类

的代码
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);
           }
    } 
}

以下是导入

import javazoom.jl.player.*;
import java.io.FileInputStream;

答案 7 :(得分:4)

为了给读者另一种选择,我建议使用JACo MP3播放器库,这是一款跨平台的java mp3播放器。

特点:

  • CPU使用率非常低(~2%)
  • 令人难以置信的小型图书馆(~90KB)
  • 不需要JMF(Java媒体框架)
  • 易于集成到任何应用程序中
  • 易于集成到任何网页(作为applet)。

有关其方法和属性的完整列表,您可以查看其文档here

示例代码:

import jaco.mp3.player.MP3Player;
import java.io.File;

public class Example1 {
  public static void main(String[] args) {
    new MP3Player(new File("test.mp3")).play();
  }
}

有关详细信息,我创建了一个简单的教程here,其中包含可下载的源代码。

答案 8 :(得分:2)

您需要先安装JMF(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();

不要忘记添加JMF jar文件

答案 9 :(得分:1)

搜索freshmeat.net获取JAVE(代表Java音频视频编码器)库(链接here)。这是一个适合这类事物的图书馆。我不知道Java是否具有本机mp3功能。

如果你想要一种方法来运行这两种类型的文件,你可能需要使用继承和一个简单的包装函数将mp3函数和wav函数包装在一起。

答案 10 :(得分:0)

要向Java Sound添加MP3阅读支持,请将JMF的mp3plugin.jar添加到应用程序的运行时类路径。

请注意,Clip类具有内存限制,使其不适合超过几秒钟的高质量声音。

答案 11 :(得分:0)

使用MP3 Decoder/player/converter Maven依赖项。

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class PlayAudio{

public static void main(String[] args) throws FileNotFoundException {

    try {
        FileInputStream fileInputStream = new FileInputStream("mp.mp3");
        Player player = new Player((fileInputStream));
        player.play();
        System.out.println("Song is playing");
        while(true){
            System.out.println(player.getPosition());
        }
    }catch (Exception e){
        System.out.println(e);
    }

  }

}

答案 12 :(得分:0)

我还有其他方法,第一种是:

public static void playAudio(String filePath){

    try{
        InputStream mus = new FileInputStream(new File(filePath));
        AudioStream aud = new AudioStream(mus);
    }catch(Exception e){
        JOptionPane.showMessageDialig(null, "You have an Error");
    }

第二个是:

try{
    JFXPanel x = JFXPanel();
    String u = new File("021.mp3").toURI().toString();
    new MediaPlayer(new Media(u)).play();
} catch(Exception e){
    JOPtionPane.showMessageDialog(null, e);
}

如果要循环播放此音频,请使用此方法。

try{
    AudioData d = new AudioStream(new FileInputStream(filePath)).getData();
    ContinuousAudioDataStream s = new ContinuousAudioDataStream(d);
    AudioPlayer.player.start(s);
} catch(Exception ex){
    JOPtionPane.showMessageDialog(null, ex);
}

如果要停止此循环,请在尝试中添加以下自由项:

AudioPlayer.player.stop(s);

对于第三种方法,我们添加以下导入:

import java.io.FileInputStream;
import sun.audio.AudioData;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;

答案 13 :(得分:0)

没有任何效果。但这个完美?

先谷歌并下载 Jlayer 库。

import javazoom.jl.player.Player;
import java.io.FileInputStream;

public class MusicPlay {

  public static void main(String[] args)  {

    try{

      FileInputStream fs = new FileInputStream("audio_file_path.mp3");
      Player player = new Player(fs);
      player.play();

    } catch (Exception e){
      // catch exceptions.
    }

  }
}

答案 14 :(得分:-1)

使用此库: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){}
}