Playing .mp3 and .wav in Java?

如何在 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文件与相同的方法。

430468 次浏览

搜索一下 freshmate.net 中的 JAVE (代表 Java 音频视频编码器)库(链接 给你)。这是这类东西的图书馆。我不知道 Java 是否有一个原生的 mp3函数。

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

我已经有一段时间没有使用它了,但是 JavaLayer对于 MP3播放是非常好的

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

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

I wrote a pure java mp3 player: mp3transform.

JavaFX 有 MediaMediaPlayer类,可以播放 mp3文件。

示例代码:

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

您将需要以下导入声明:

import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

You need to install JMF first (使用此连结下载)

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

你只能用 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

使用标准 javax.sound API,轻量级 Maven 依赖,完全开源(Java 7或更高版本) ,这应该能够播放大多数 WAV,OGG Vorbis 和 MP3文件:

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

参考文献 :

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

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

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

所需进口:

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

这就是你开始演奏音乐所需要的。播放器启动和管理自己的播放线程,并提供 播放,暂停,继续,停止寻找功能。

对于更高级的用法,您可以看看吉贵音乐播放器。这是一个开源的 WinAmp 克隆: http://www.javazoom.net/jlgui/jlgui.html

The first class to look at would be PlayerUI (inside the package javazoom.jlgui.player.amp). 它很好地演示了 BasicPlayer 的高级特性。

我发现的最简单的方法是从 http://www.javazoom.net/javalayer/sources.html下载 JLayerjar 文件并将其添加到 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;

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

特点:

  • 非常低的 CPU 使用率(约2%)
  • 令人难以置信的小型图书馆(约90KB)
  • doesn't need JMF (Java Media Framework)
  • 易于集成到任何应用程序中
  • 易于集成在任何网页(作为小程序)。

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

示例代码:

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

For more details, I created a simple tutorial here that includes a downloadable sourcecode.

更新(2022)

那个页面上的下载链接已经不工作了,但是有一个 源泉锻造项目

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

使用 MP3解码器/播放器/转换器 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);
}


}


}

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

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

if we want to stop this loop we add this libreries in the try:

AudioPlayer.player.stop(s);

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

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

什么都没用,但这个很完美

谷歌和下载 Jlayerlibrary 第一。

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.
}


}
}