Search code examples
javajavafxmedia-player

Unable to play video using JavaFX MediaPlayer


In my fxml file I have:

<AnchorPane prefHeight="500.0" prefWidth="500.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.40">
   <children>
      <Button layoutX="14.0" layoutY="461.0" mnemonicParsing="false" text="Dummy Button" />
      <MediaView id="videoView" fitHeight="400.0" fitWidth="450.0" layoutX="14.0" layoutY="14.0" />
   </children>
</AnchorPane>

And here is my code:

File f = new File("video.mp4");
Media media = new Media(f.toURI().toString());

MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.setAutoPlay(true);

MediaView mediaView = (MediaView) videoLayout.lookup("#videoView");
mediaView.setMediaPlayer(mediaPlayer);

Dummy button appears so layout is loaded correctly. There are no exceptions or errors but still nothing happens. I don't see any video frame, nothing is being played. I'm running that code on Windows 7. What am I doing wrong?

EDIT:

Code is ok. Just not all of my test content was supported. As suggested below it's good to check player state:

mediaPlayer.setOnError(()->System.out.println("media error"
    + mediaPlayer.getError().toString()));

I've met 3 issues so far:

  1. Error was printed "ERROR_MEDIA_CORRUPTED: ERROR_MEDIA_CORRUPTED"
  2. No error was printed but only audio played
  3. Exception was thrown "MediaException: MEDIA_UNSUPPORTED : Unrecognized file signature!"

Solution

  • Check that the media is supported:

    mediaPlayer.setOnError(()->
        System.out.println("media error"+mediaPlayer.getError().toString()));
    

    If there's a MediaException, like audio format unsupported, you won't see the video, but the application will launch normally.

    Note that you could try this other approach, embedding all the code in the FXML file:

    <MediaView id="videoView" fitHeight="400.0" fitWidth="450.0" layoutX="14.0" layoutY="14.0">
        <mediaPlayer>
            <MediaPlayer autoPlay="true">
                <media>
                    <Media source="@video.mp4" />
                </media>
            </MediaPlayer>
        </mediaPlayer>    
    </MediaView>