2

How do I use MediaPlayer to play m4a files? This is my code:

public void audioPlayerButtons(ActionEvent actionEvent) {
       String bip = "Songs/01 Clarity.m4a";
       Media hit = new Media(bip);
       MediaPlayer mediaPlayer = new MediaPlayer(hit);

       if (actionEvent.getSource() == playbtn) {
           mediaPlayer.play();

       } else if (actionEvent.getSource() == pausebtn) {
           mediaPlayer.pause();

       } else if (actionEvent.getSource() == forwardbtn) {
           mediaPlayer.stop();

       } else if (actionEvent.getSource() == backwardbtn) {
           mediaPlayer.isAutoPlay();
       }

but it's throwing an error:

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1762)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1645)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)

could you please help me understand why?

Basically, my aim is to make a mp3 player using mediaPlayer

xox
  • 23
  • 2

1 Answers1

1

According to the Javadocs for the Media constructor:

The source must represent a valid URI and is immutable. Only HTTP, FILE, and JAR URLs are supported. If the provided URL is invalid then an exception will be thrown.

The value you provided ("Songs/01 Clarity.m4a") is certainly not a valid URI, as it has whitespace.

You need something like

String bip = getClass().getResource("Songs/01 Clarity.m4a").toExternalForm();

(which will try to find the song relative to the current class, and is useful if you intend to bundle the m4a files with your application), or

String bip = new File("Songs/01 Clarity.m4a").toURI().toString();

which will look for the file on the file system, relative to the working directory.

In either case, you will likely need to change the path to get it correct.

James_D
  • 201,275
  • 16
  • 291
  • 322