Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
856 views
in Technique[技术] by (71.8m points)

audio - How to play an mp3 file in java

I am trying to play a song (mp3 file) in java. I have been looking around for a few hours now and none of the ways I found worked properly.

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

I have tried doing that but it gives me errors.

I have imported JMF and JLayer.

I have also read other questions that are like this one on this forum and none of them have helped me.

I just need a hand to help play an mp3 file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For this you'll need to install Java Media Framework (JMF) in your PC. One you have it installed,then try this piece of code:

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

You may run into unable to handle formaterror, that is because Java took out the MP3 support by default (pirate copyright issue), you are required to install a “JMF MP3 plugin” in order to play MP3 file.

Go Java’s JMF website to download it http://java.sun.com/javase/technologies/desktop/media/jmf/mp3/download.html

To be sure that you are using a supported format file, check here:

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

If you are using windows7, you may have to read this as well:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...