Example usage for javafx.scene.media MediaPlayer MediaPlayer

List of usage examples for javafx.scene.media MediaPlayer MediaPlayer

Introduction

In this page you can find the example usage for javafx.scene.media MediaPlayer MediaPlayer.

Prototype

public MediaPlayer(@NamedArg("media") Media media) 

Source Link

Document

Create a player for a specific media.

Usage

From source file:Main.java

private void createMedia() {
    try {/*from w w  w  .j  a v  a 2 s. c o m*/
        media = new Media("http://traffic.libsyn.com/dickwall/JavaPosse373.mp3");
        media.getMetadata().addListener(new MapChangeListener<String, Object>() {
            @Override
            public void onChanged(Change<? extends String, ? extends Object> ch) {
                if (ch.wasAdded()) {
                    handleMetadata(ch.getKey(), ch.getValueAdded());
                }
            }
        });

        mediaPlayer = new MediaPlayer(media);
        mediaPlayer.setOnError(new Runnable() {
            @Override
            public void run() {
                final String errorMessage = media.getError().getMessage();
                // Handle errors during playback
                System.out.println("MediaPlayer Error: " + errorMessage);
            }
        });

        mediaPlayer.play();

    } catch (RuntimeException re) {
        // Handle construction errors
        System.out.println("Caught Exception: " + re.getMessage());
    }
}

From source file:com.tesshu.subsonic.client.sample4_music_andmovie.StreamDownloadAndPlayApplication.java

@Override
public void start(Stage stage) throws Exception {

    Search2Controller search2 = context.getBean(Search2Controller.class);

    StreamController streamController = context.getBean(StreamController.class);

    SuccessObserver callback = context.getBean(SuccessObserver.class);

    File tmpDirectory = new File(tmpPath);
    tmpDirectory.mkdir();/*from w w w .  j a  v  a 2 s.  c  o  m*/

    Optional<SearchResult2> result2 = search2.getOf("e", null, null, null, null, 1, null, null);

    result2.ifPresent(result -> {
        Optional<Child> maybeSong = result.getSongs().stream().findFirst();
        maybeSong.ifPresent(song -> {

            streamController.stream(song, maxBitRate, format, null, null, null, null,
                    (subject, inputStream, contentLength) -> {

                        File dir = new File(
                                tmpPath + "/" + song.getPath().replaceAll("([^/]+?)?$", StringUtils.EMPTY));
                        dir.mkdirs();

                        File file = new File(tmpPath + "/"
                                + song.getPath().replaceAll("([^.]+?)?$", StringUtils.EMPTY) + format);

                        try {
                            BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
                            BufferedInputStream reader = new BufferedInputStream(inputStream);

                            byte buf[] = new byte[256];
                            int len;
                            while ((len = reader.read(buf)) != -1) {
                                fos.write(buf, 0, len);
                            }
                            fos.flush();
                            fos.close();
                            reader.close();
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        String path = Paths.get(file.getPath()).toUri().toString();
                        Group root = new Group();
                        Scene scene = new Scene(root, 640, 480);
                        Media media = new Media(path);
                        MediaPlayer player = new MediaPlayer(media);
                        MediaView view = new MediaView(player);
                        ((Group) scene.getRoot()).getChildren().add(view);
                        stage.setScene(scene);
                        stage.show();

                        player.play();

                    }, callback);

        });

    });
}

From source file:com.tesshu.subsonic.client.sample4_music_andmovie.StreamDownloadAndPlayWithThreadApplication.java

@Override
public void start(Stage stage) throws Exception {

    Search2Controller search2 = context.getBean(Search2Controller.class);

    StreamController streamController = context.getBean(StreamController.class);

    SuccessObserver callback = context.getBean(SuccessObserver.class);

    SearchResult2 result2 = search2.get("e", null, null, null, null, 1, null, null);

    List<Child> songs = result2.getSongs();

    File tmpDirectory = new File(tmpPath);
    tmpDirectory.mkdir();// w ww  .  jav  a2s.  c  om

    int maxBitRate = 256;

    Child song = songs.get(0);

    new Thread(new Runnable() {
        public void run() {
            try {

                streamController.stream(song, maxBitRate, format, null, null, null, null,

                        (subject, inputStream, contentLength) -> {

                            File dir = new File(
                                    tmpPath + "/" + song.getPath().replaceAll("([^/]+?)?$", StringUtils.EMPTY));
                            dir.mkdirs();

                            file = new File(tmpPath + "/"
                                    + song.getPath().replaceAll("([^.]+?)?$", StringUtils.EMPTY) + format);

                            try {

                                FileOutputStream fos = new FileOutputStream(file);
                                BufferedInputStream reader = new BufferedInputStream(inputStream);

                                byte buf[] = new byte[256];
                                int len;
                                while ((len = reader.read(buf)) != -1) {
                                    fos.write(buf, 0, len);
                                }
                                fos.flush();
                                fos.close();
                                reader.close();
                                inputStream.close();

                                LOG.info("download finished");

                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }, callback);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

    LOG.info("download thread start");

    new Thread(new Runnable() {
        public void run() {
            while (file == null || file.getPath() == null) {
                LOG.info("wait file writing.");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                String path = Paths.get(file.getPath()).toUri().toString();
                Group root = new Group();
                Scene scene = new Scene(root, 640, 480);
                Media media = new Media(path);
                MediaPlayer player = new MediaPlayer(media);
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            while (MediaPlayer.Status.READY != player.getStatus()) {
                                LOG.info(player.getStatus() + " : " + path);
                                LOG.info(media.errorProperty());
                                Thread.sleep(1000);
                                if (MediaPlayer.Status.PLAYING == player.getStatus()) {
                                    LOG.info(player.getStatus() + " : " + path);
                                    break;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

                MediaView view = new MediaView(player);
                ((Group) scene.getRoot()).getChildren().add(view);

                Platform.runLater(() -> {
                    stage.setScene(scene);
                    stage.show();
                    player.play();
                });

            }
        }
    }).start();

}

From source file:smarthome.FXMLDocumentController.java

private void initPlayer(String uri) {

    Media media = new Media(uri);
    MediaPlayer mediaPlayer = new MediaPlayer(media);
    mediaPlayer.setAutoPlay(true);// w w  w.  j  ava2 s.c  o  m
    videoView.setMediaPlayer(mediaPlayer);
    mediaPlayer.play();
    /* mediaPlayer.setOnReady(new Runnable() {
    @Override
    public void run() {
        // TODO Auto-generated method stub
    }
     });*/
}

From source file:MediaControl.java

@Override
public void start(Stage primaryStage) {
    primaryStage.setTitle("Embedded Media Player");
    Group root = new Group();
    Scene scene = new Scene(root, 540, 241);

    // create media player
    Media media = new Media((arg1 != null) ? arg1 : MEDIA_URL);
    MediaPlayer mediaPlayer = new MediaPlayer(media);
    mediaPlayer.setAutoPlay(true);//from w  w  w  . ja v  a2 s  .  c om

    MediaControl mediaControl = new MediaControl(mediaPlayer);
    scene.setRoot(mediaControl);

    primaryStage.setScene(scene);
    primaryStage.show();
}

From source file:Jigs_Desktop_Client.GUI.FXMLDocumentController.java

private void alert(String fileName) {
    Media sound;/*  w  w w  . j a  v  a 2s .c  om*/
    try {
        sound = new Media(FXMLDocumentController.class.getResource(fileName).toURI().toString());
        MediaPlayer mediaPlayer = new MediaPlayer(sound);
        mediaPlayer.play();
    } catch (URISyntaxException ex) {
        Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:co.anarquianegra.rockolappServidor.mundo.ListaReproductor.java

/**
 * Reproduece la siguiente cancion en la cola
 *///from w w w  . j a  v a 2s .c o  m
public synchronized void reproducir() {
    playing = true;
    if (mediaPlayer != null && mediaPlayer.getStatus().equals(Status.PAUSED)) {
        mediaPlayer.play();
    } else {
        if (listaReproduccion.size() > 0) {
            String path = sacarPathCancion();
            System.out.println("Path = " + path);
            media = new Media(path);
            mediaPlayer = new MediaPlayer(media);
            mediaPlayer.setOnEndOfMedia(new Runnable() {
                @Override
                public void run() {
                    setOnMedia();
                }
            });
            mediaPlayer.play();
        }
    }
}

From source file:co.anarquianegra.rockolappServidor.mundo.ListaReproductor.java

private void setOnMedia() {
    System.out.println("------------EndOfMedia----------");
    mediaPlayer.dispose();/* ww  w . j  av  a  2s  .  co m*/
    System.out.println("Dispose Status: " + mediaPlayer.getStatus());
    if (listaReproduccion.size() > 0) {
        listaReproduccion.remove(0);
    }
    if (listaReproduccion.size() > 0) {
        String path = sacarPathCancion();
        media = new Media(path);
        mediaPlayer = new MediaPlayer(media);
        mediaPlayer.setOnEndOfMedia(new Runnable() {
            @Override
            public void run() {
                setOnMedia();
            }
        });
        mediaPlayer.play();
    }
}

From source file:AudioPlayer3.java

private void initializeMedia(String url) {
    resetProperties();//  ww w. j  a  va 2  s  .  c om

    try {
        final Media media = new Media(url);
        media.getMetadata().addListener(new MapChangeListener<String, Object>() {
            @Override
            public void onChanged(Change<? extends String, ? extends Object> ch) {
                if (ch.wasAdded()) {
                    handleMetadata(ch.getKey(), ch.getValueAdded());
                }
            }
        });

        mediaPlayer.setValue(new MediaPlayer(media));
        mediaPlayer.get().setOnError(new Runnable() {
            @Override
            public void run() {
                String errorMessage = mediaPlayer.get().getError().getMessage();
                // Handle errors during playback
                System.out.println("MediaPlayer Error: " + errorMessage);
            }
        });
    } catch (RuntimeException re) {
        // Handle construction errors
        System.out.println("Caught Exception: " + re.getMessage());
    }
}

From source file:com.spankingrpgs.model.GameState.java

/**
 * Start playing the music with the specified name.
 *
 * @param music  The name of the music to play
 * @param restart  If true, the music specified will be played from the beginning even if it is already playing,
 * if false then the music will not be restarted if already playing
 *//*from   ww w .jav  a2 s  .co  m*/
public void startMusic(String music, boolean restart) {
    if (musicName != null && !restart && musicName.equals(music)) {
        return;
    }
    stopMusic();
    musicName = music;
    MusicMap musicMap = MusicMap.INSTANCE;
    if (musicMap.get(musicName) == null) {
        LOG.warning(String.format("No music for %s found. MusicMap: %s", music, musicMap));
        return;
    }
    MusicMap.mediaPlayer = new MediaPlayer(MusicMap.INSTANCE.get(music));
    MusicMap.mediaPlayer.setCycleCount(MediaPlayer.INDEFINITE);
    MusicMap.mediaPlayer.play();
}