在Java中播放.mp3和.wav ?

时间:2021-07-18 15:59:11

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:

如何在Java应用程序中播放.mp3和.wav文件?我用摇摆。我试着在网上搜索,比如这个例子:

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.

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

The same with:

同样的:

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

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.

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

12 个解决方案

#1


101  

Java FX has Media and MediaPlayer classes which will play mp3 files.

Java FX有媒体和MediaPlayer类,可以播放mp3文件。

Example code:

示例代码:

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

You will need the following import statements:

您将需要以下导入语句:

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

#2


30  

I wrote a pure java mp3 player: mp3transform.

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

#3


16  

you can play .wav only with java API:

您可以只使用java API进行。wav:

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

code:

代码:

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

And play .mp3 with jLayer

播放。mp3和jLayer。

#4


15  

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

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

#5


12  

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

我建议使用BasicPlayerAPI。它是开源的,非常简单,不需要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:

下载并提取zip文件后,应将以下jar文件添加到项目的构建路径:

  • basicplayer3.0.jar
  • basicplayer3.0.jar
  • all the jars from the lib directory (inside BasicPlayer3.0)
  • 所有来自lib目录的jar文件(在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

对于更高级的用法,您可以查看一下jlGui音乐播放器。它是一个开源的WinAmp克隆: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.

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

#6


9  

Using standard javax.sound API, a single Maven dependency, completely Open Source (Java 7 required) :

使用标准javax。声音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>

Code

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

References:

#7


4  

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

我找到的最简单的方法是从http://www.javazoom.net/javalayer/sources.html下载JLayer jar文件,并将其添加到jar库http://www.wikihow.com/add - jar -to- projects - build - paths -% 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;

#8


3  

To give the readers another alternative, I am suggesting JACo MP3 Player library, a cross platform java mp3 player.

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

Features:

特点:

  • very low CPU usage (~2%)
  • 极低的CPU使用率(~2%)
  • incredible small library (~90KB)
  • 令人难以置信的小型图书馆(~ 90 kb)
  • doesn't need JMF (Java Media Framework)
  • 不需要JMF (Java媒体框架)
  • easy to integrate in any application
  • 易于集成到任何应用程序中
  • easy to integrate in any web page (as applet).
  • 易于集成在任何web页面(作为applet)。

For a complete list of its methods and attributes you can check its documentation here.

关于它的方法和属性的完整列表,您可以在这里查看它的文档。

Sample code:

示例代码:

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.

关于更多细节,我在这里创建了一个简单的教程,其中包含可下载的源代码。

#9


2  

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

您需要先安装JMF(使用此链接下载)

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

不要忘记添加JMF jar文件

#10


1  

Use this library: import sun.audio.*;

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

#11


0  

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.

为JAVE(代表Java音频视频编码器)库(这里有链接)搜索freshmeat.net。这是一个存放这些东西的图书馆。我不知道Java是否有一个本地mp3功能。

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.

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

#12


0  

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

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

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

注意,Clip类具有内存限制,这使得它不适用于几秒以上的高质量声音。

#1


101  

Java FX has Media and MediaPlayer classes which will play mp3 files.

Java FX有媒体和MediaPlayer类,可以播放mp3文件。

Example code:

示例代码:

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

You will need the following import statements:

您将需要以下导入语句:

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

#2


30  

I wrote a pure java mp3 player: mp3transform.

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

#3


16  

you can play .wav only with java API:

您可以只使用java API进行。wav:

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

code:

代码:

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

And play .mp3 with jLayer

播放。mp3和jLayer。

#4


15  

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

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

#5


12  

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

我建议使用BasicPlayerAPI。它是开源的,非常简单,不需要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:

下载并提取zip文件后,应将以下jar文件添加到项目的构建路径:

  • basicplayer3.0.jar
  • basicplayer3.0.jar
  • all the jars from the lib directory (inside BasicPlayer3.0)
  • 所有来自lib目录的jar文件(在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

对于更高级的用法,您可以查看一下jlGui音乐播放器。它是一个开源的WinAmp克隆: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.

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

#6


9  

Using standard javax.sound API, a single Maven dependency, completely Open Source (Java 7 required) :

使用标准javax。声音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>

Code

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

References:

#7


4  

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

我找到的最简单的方法是从http://www.javazoom.net/javalayer/sources.html下载JLayer jar文件,并将其添加到jar库http://www.wikihow.com/add - jar -to- projects - build - paths -% 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;

#8


3  

To give the readers another alternative, I am suggesting JACo MP3 Player library, a cross platform java mp3 player.

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

Features:

特点:

  • very low CPU usage (~2%)
  • 极低的CPU使用率(~2%)
  • incredible small library (~90KB)
  • 令人难以置信的小型图书馆(~ 90 kb)
  • doesn't need JMF (Java Media Framework)
  • 不需要JMF (Java媒体框架)
  • easy to integrate in any application
  • 易于集成到任何应用程序中
  • easy to integrate in any web page (as applet).
  • 易于集成在任何web页面(作为applet)。

For a complete list of its methods and attributes you can check its documentation here.

关于它的方法和属性的完整列表,您可以在这里查看它的文档。

Sample code:

示例代码:

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.

关于更多细节,我在这里创建了一个简单的教程,其中包含可下载的源代码。

#9


2  

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

您需要先安装JMF(使用此链接下载)

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

不要忘记添加JMF jar文件

#10


1  

Use this library: import sun.audio.*;

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

#11


0  

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.

为JAVE(代表Java音频视频编码器)库(这里有链接)搜索freshmeat.net。这是一个存放这些东西的图书馆。我不知道Java是否有一个本地mp3功能。

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.

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

#12


0  

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

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

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

注意,Clip类具有内存限制,这使得它不适用于几秒以上的高质量声音。