Sunday 10 June 2007

Mp3 Playback in Java

Setting this up took a while and I can't really be sure exactly what I did to get all the things working; if I ever do a clean install, I'll try and document the process. Here's a very quick outline before I post the code -

I grabbed all the jars from here:
http://java.sun.com/products/java-media/jmf/2.1.1/download.html
And grabbed the mp3 handler here:
http://java.sun.com/products/java-media/jmf/mp3/download.html

The jars you'll need to drop into eclipse are (I think):
mp3plugin.jar
mediaplayer.jar
jmf.jar
multiplayer.jar

Here were some other links I found handy:
http://java.sun.com/products/java-media/jmf/2.1.1/setup-linux.html
http://java.sun.com/products/java-media/jmf/2.1.1/jmfdiagnostics.html
http://ubuntuforums.org/showthread.php?t=436053
http://weblogs.java.net/blog/jonathansimon/archive/2004/11/suns_mp3_plugin.html
http://forum.java.sun.com/thread.jspa?threadID=686681&messageID=3996185

Just a prewarning:
I kept getting errors that looked like this -
Unable to handle format: mpeglayer3, 44100.0 Hz, 16-bit, Stereo,
LittleEndian, Signed, 16000.0 frame rate, FrameSize=32768 bits
Failed to realize: com.sun.media.PlaybackEngine@12dd76
Error: Unable to realize com.sun.media.PlaybackEngine@12dd76
Failed to realize: input media not supported: mpeglayer3 audio

If you keep seeing these, try a number of different mp3 files; I had to try 3 before I had something working. I found testing the mp3 files using jmstudio was a reliable way to test - if jmstudio can open and play the file automatically, then it should work fine with the code listed below.

You can see a forum discussion regarding some of the common problems here:
http://www.velocityreviews.com/forums/t149533-mp3-playback-using-java-sound-and-sun-mp3-plugin.html

A common alternative to the sun offering seems to be:
http://www.tritonus.org/plugins.html

-----------------------------------------------------
Ok - if everything is set up and appears to be working, you can try some of these classes. I found the original examples by looking around on forums, but had to make some changes to get them to work completely.

The simplest example I could find of a java class able to play an mp3 file:




Another example I found in a few forums used this code as a base:
http://forum.java.sun.com/thread.jspa?threadID=625352&messageID=3565801

I had to make a few modifications to get the code to work. Here is the class:



To test the class, I created a calling class called TestPlayMp3Thread:



Hope this is useful for someone else.

2 comments:

Unknown said...

This helped me alot, thank you very much

chandrasekhar's said...

sorry sir i tried several times and gave much of mp3 but it says same..