2

Using Applet.AudioClip I'm able to play .wav files, but if I try to do that on an MP3 file, then no audio seems to get played even though no exceptions are thrown.

Is there any way to play MP3s with Java, whether using Swing, Java FX, or any other Java technologies?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Ali
  • 261,656
  • 265
  • 575
  • 769

1 Answers1

3
package test;

import java.io.File;

import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.PlugInManager;
import javax.media.format.AudioFormat;

public class AudioTest {
public static void main(String[] args) {
    Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
    Format input2 = new AudioFormat(AudioFormat.MPEG);
    Format output = new AudioFormat(AudioFormat.LINEAR);
    PlugInManager.addPlugIn(
        "com.sun.media.codec.audio.mp3.JavaDecoder",
        new Format[]{input1, input2},
        new Format[]{output},
        PlugInManager.CODEC
    );
    try{
        Player player = Manager.createPlayer(new MediaLocator(new File("data/audioFiles/abc.mp3").toURI().toURL()));
        player.start();
    }
    catch(Exception ex){
        ex.printStackTrace();
    }
}
}

Hope it helps..

Tapan Desai
  • 848
  • 2
  • 14
  • 36
  • See also [this answer](http://stackoverflow.com/questions/9470148/how-do-you-play-a-long-audio-clip-in-java/9470886#9470886) which combines the MP3 SPI of JMF with Java Sound. – Andrew Thompson Sep 06 '12 at 04:59
  • 1
    `import javax.media.Format;` is giving me an error saying no such package `javax.media`? I have javafx 2.1.1 installed – Ali Sep 06 '12 at 05:02
  • @AndrewThompson try the package `import javax.media.format.AudioFormat;` – Tapan Desai Sep 06 '12 at 05:07
  • JavaFX package names are prefixed with `javafx` (you might notice that if you ever examined the Java Docs, or the imports for a JavaFX project..). The above code is pure JMF. – Andrew Thompson Sep 06 '12 at 05:14
  • @Tapan I am guessing you meant that comment to the person who asked the question. I use the JMF SPI for playing MP3, and it does not need to be imported in the code, just put on the run-time class-path. – Andrew Thompson Sep 06 '12 at 05:16