Making a music player using JMF may seem a bit complex. There are a few Open Source libs that will help you out. I have made a collection of these and they are freely available here: Music Libraries
After downloading, you need to create a Java project in your favorite IDE and set these libs in your project classpath. (These libs are development from JavaZoom, JLayer MP3 API.) Now after all these are done, a simple code will play your song.
BasicPlayer myMusicPlayer=new BasicPlayer();
BasicController playerController =(BasicController)myMusicPlayer;
String filePath="D:/SexyTracks/Just_dance.mp3";
File file=new File(filePath);
try
{
playerController.open(file);
playerController.play();
}catch(Exception ex){}
To pause or stop the song:
try
{
if(choice)
playerController.pause();
else
playerController.stop();
}catch(Exception ex){}
Or you might like to set the volume using:
playerController.setGain(0.85);
Remember one thing. Whatever you do with the controller, don't forget to surround it with try
/catch
blocks. The API creates a separate thread for each song that gets played, so you don't need to worry about creating a new thread.
In case you need to know how much of the song has been played so far or when the song was opened, paused, or anything, you need a BasicPlayerListener
. In the class where you are playing the song, make it implement BasicPlayerListener
.
class MyMusicPlayer implements BasicPlayerListener
And add these method stubs (you will need others also according to your purpose):
public void opened(Object stream, Map properties)
{
}
public void progress(int bytesread, long microseconds, byte[] pcmdata, Map properties)
{
long time=microseconds/(1000*1000);
System.out.println(time);
}
In case you need a speed up, here's my simple NetBeans project[^] for you.
I think this will warm you up enough to get started with this strong music library from JavaZoom[^].:)
N.B.: The way described here will enable you to play MP3 files only. To be able to play other file types, include the full set of libs I mentioned before in your project classpath.
Don't forget to let me know your steps.