如何在java中播放mp3文件

我想在java中播放一首歌(mp3文件)。 我一直在寻找几个小时,我发现的方法都没有正常工作。

public void play() { String song = "song.mp3"; Media track = new Media(song); MediaPlayer mediaPlayer = new MediaPlayer(track); mediaPlayer.play(); } 

我试过这样做,但它给了我错误。

我导入了JMFJLayer

我也在这个论坛上读过其他类似的问题,但没有人帮助过我。

我只需要一只手帮助播放一个mp3文件。

为此,您需要在PC中安装Java Media Framework(JMF) 。 一个你安装它,然后尝试这段代码:

 import javax.media.*; import java.net.*; import java.io.*; import java.util.*; class AudioPlay { public static void main(String args[]) throws Exception { // Take the path of the audio file from command line File f=new File("song.mp3"); // Create a Player object that realizes the audio final Player p=Manager.createRealizedPlayer(f.toURI().toURL()); // Start the music p.start(); // Create a Scanner object for taking input from cmd Scanner s=new Scanner(System.in); // Read a line and store it in st String st=s.nextLine(); // If user types 's', stop the audio if(st.equals("s")) { p.stop(); } } } 

您可能遇到无法处理formaterror,因为Java默认情况下取消了MP3支持(盗版版权问题),您需要安装“JMF MP3插件”才能播放MP3文件。

去Java的JMF网站下载它http://java.sun.com/javase/technologies/desktop/media/jmf/mp3/download.html

要确保您使用的是受支持的格式文件,请在此处查看:

http://www.oracle.com/technetwork/java/javase/formats-138492.html

如果您使用的是Windows7,则可能还必须阅读:

https://forums.oracle.com/forums/thread.jspa?threadID=2132405&tstart=45

我发现最简单的方法是从http://www.javazoom.net/javalayer/sources.html下载JLayer jar文件并将其添加到Jar库http://www.wikihow.com/Add-JARs-对项目-建造-路径-在-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

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

JavaFX应用程序如何 –

 import java.net.URL; import javafx.application.Application; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.stage.Stage; public class VLC extends Application { void playMedia() { String mp3 = "00- Tu Hi Mera.mp3"; URL resource = getClass().getResource(mp3); System.out.println(resource.toString()); Media media = new Media(resource.toString()); MediaPlayer mediaPlayer = new MediaPlayer(media); mediaPlayer.play(); } public static void main(String args[]) { new VLC().playMedia(); } @Override public void start(Stage stage) throws Exception { } }