Format error when trying to play MP3 in Java with JMF

693 Views Asked by At

I have an error when I try to play an MP3 file in Java using JMF. I have tried with a WAV file and it works well.

Here is my code (based on this tutorial):

import javax.media.*;
import java.net.URL;

class mp3 extends Thread {
    private URL url;
    private Player playMP3;

    public mp3(String mp3) {
        try {
            this.url = new URL(mp3);
        } catch (java.net.MalformedURLException e) {
            System.out.println(e.getMessage());
        }
    }

    public void run() {

        try {
            MediaLocator mediaLocator = new MediaLocator(url);
            playMP3 = Manager.createPlayer(mediaLocator);
        } catch (java.io.IOException | NoPlayerException e) {
            System.out.println(e.getMessage());
        }

        playMP3.addControllerListener(new ControllerListener() {
            public void controllerUpdate(ControllerEvent e) {
                if (e instanceof EndOfMediaEvent) {
                    playMP3.stop();
                    playMP3.close();
                }
            }
        });
        playMP3.realize();
        playMP3.start();
    }
}

public class PlayMP3 {
    public static void main(String[] args) {
        mp3 t = new mp3("file:///C://TestMP3Player//music.wav"); // Works well
//      mp3 t = new mp3("file:///C://TestMP3Player//music.mp3"); // Doesn't work (error below)
        t.start();
        System.out.println("Playing song...");
    }
}

And the error (the same as in this post):

Playing song... 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@54932122 Error: Unable to realize com.sun.media.PlaybackEngine@54932122

Process finished with exit code 0

I do not know if I installed JMF correctly. I just add the JMF-2.1.1e\lib directory that contains the JAR files in the project dependancies in IntelliJ like this:

IntelliJ project dependancies window

An idea of what makes this mistake?

Thank you for your help!

2

There are 2 best solutions below

0
RalleYTN On

Seems the MP3 file is in a format that JMF can't handle. Luckily for you I have an audio library which is also able to play MP3 files.

https://github.com/RalleYTN/SimpleAudio

0
hoymkot On

The following is all I need to play mp3.

public static void main(String args[]) throws NoPlayerException, CannotRealizeException, IOException {
    MediaLocator ml = new MediaLocator((new File("roar_of_future.mp3").toURL()));
    Player player = Manager.createRealizedPlayer(ml);
    player.start();
}

So please make sure

  1. mp3plugin.jar and jmf.jar is in the classpath
  2. JavaSDK is Java 8 (32bit) or 7 (32bit) because JMF is not working on Java 9 and above. library