Java – Playing MP3 and MP4

Here’s one way to trigger an MP3 or MP4 simply in one go:

MP4:

Just stick a jPanel somewhere (jPanelVideo in this example):

        // TODO add your handling code here:
        final JFXPanel VFXPanel = new JFXPanel();

        File video_source = new File("ponponpon.mp4");
        Media m = new Media(video_source.toURI().toString());
        MediaPlayer player = new MediaPlayer(m);
        MediaView viewer = new MediaView(player);

        StackPane root = new StackPane();
        Scene scene = new Scene(root);

        // center video position
        javafx.geometry.Rectangle2D screen = Screen.getPrimary().getVisualBounds();
        viewer.setX((screen.getWidth() - jPanelVideo.getWidth()) / 2);
        viewer.setY((screen.getHeight() - jPanelVideo.getHeight()) / 2);

        // resize video based on screen size
        DoubleProperty width = viewer.fitWidthProperty();
        DoubleProperty height = viewer.fitHeightProperty();
        width.bind(Bindings.selectDouble(viewer.sceneProperty(), "width"));
        height.bind(Bindings.selectDouble(viewer.sceneProperty(), "height"));
        viewer.setPreserveRatio(true);

        // add video to stackpane
        root.getChildren().add(viewer);

        VFXPanel.setScene(scene);
        player.play();
        jPanelVideo.setLayout(new BorderLayout());
        jPanelVideo.add(VFXPanel, BorderLayout.CENTER);

MP3:

Uses JavaZOOM JLayer library.

            FileInputStream file = null;
            try {
                file = new FileInputStream("test.mp3");
            } catch (FileNotFoundException ex) {
                Logger.getLogger(LaunchPadForm.class.getName()).log(Level.SEVERE, null, ex);
            }

            Player playMP3 = null;
            try {
                playMP3 = new Player(file);
            } catch (JavaLayerException ex) {
                Logger.getLogger(LaunchPadForm.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                playMP3.play();

            } catch (JavaLayerException ex) {
                Logger.getLogger(LaunchPadForm.class.getName()).log(Level.SEVERE, null, ex);
            }

 

Leave a Reply

Your email address will not be published. Required fields are marked *