播放MP3播放和.wav在Java中?

问题描述 投票:102回答:12

我怎样才能发挥.mp3,在我的Java应用程序一个.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();
    }
}

但是,这只会起到.wav文件。

同样有:

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

我希望能够用同样的方法,发挥双方.mp3文件和.wav文件。

java audio mp3 wav
12个回答
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 java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

1
投票

做JAVE搜索freshmeat.net的(代表Java音频视频编码器)库(链接here)。这对这些事情的库。我不知道,如果Java有一个天然的MP3功能。

你可能会需要包装的MP3功能和WAV功能一起使用继承和一个简单的包装功能,如果你想一个方法来运行这两种类型的文件。


1
投票

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

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

  }

}

0
投票

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

需要注意的是Clip类有内存的限制,使得它不适合比高质量的声音几秒钟。


-1
投票

使用这个库:进口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){}
}

30
投票

我写了一个纯Java的MP3播放器:mp3transform


18
投票

你可以播放.wav只能在Java API:

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

并发挥.MP3与jLayer


15
投票

它已经有一段时间,因为我用它,但JavaLayer MP3播放是伟大的


13
投票

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

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

  • basicplayer3.0.jar
  • 一切从lib目录罐子(内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的高级功能相当不错。


13
投票

使用标准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>

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:


5
投票

我发现最简单的方法是从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;

4
投票

为了给读者另一种选择,我建议雅科MP3播放器库,跨平台的Java MP3播放器。

特征:

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

对于其方法的完整列表和属性,你可以检查它的文档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包括一个可下载的源代码。


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文件

© www.soinside.com 2019 - 2024. All rights reserved.