Example usage for javafx.scene.media Media Media

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

Introduction

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

Prototype

public Media(@NamedArg("source") String source) 

Source Link

Document

Constructs a Media instance.

Usage

From source file:Main.java

private void createMedia() {
    try {//  w ww.  ja va2s . 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:benedict.zhang.addon.soundmanager.controller.SoundManagerConfigureController.java

@Override
public void handle(WindowEvent event) {
    Sound dbSound = null;/*from ww  w  . j  a  va 2  s. c  o m*/
    if (WindowEvent.WINDOW_SHOWN.equals(event.getEventType())) {
        try {
            dbSound = SoundDataProxy.getInstance().getDataSound(ApplicationUIConstants.SOUND_INFO,
                    Boolean.TRUE);
            BeanUtils.copyProperties(sound, dbSound);
            Media media = new Media(new File(sound.getSoundPath()).toURI().toURL().toString());
            if (media != null) {
                mediaPlayer = new MediaPlayer(media);
                mediaPlayer.setOnPlaying(() -> {
                    btnSoundPlayPause.setText("Pause");
                    this.sound.setTotalDuration(mediaPlayer.getTotalDuration());
                });
                mediaPlayer.setOnPaused(() -> {
                    btnSoundPlayPause.setText("Play");
                });
                mediaPlayer.setOnStopped(() -> {
                    btnSoundPlayPause.setText("Play");
                });
                mediaPlayer.setOnEndOfMedia(() -> {
                    btnSoundPlayPause.setText("Play");
                    mediaPlayer.stop();
                });
                configMediaView.setMediaPlayer(mediaPlayer);
                String mediaInfo = sound.getSoundPath();
                soundFileName.setText(mediaInfo);
                mediaPlayer.play();
            }
        } catch (MalformedURLException ex) {
            this.dialog.hide();
        } catch (IllegalAccessException ex) {
            this.dialog.hide();
        } catch (InvocationTargetException ex) {
            this.dialog.hide();
        } catch (MediaException me) {
            if (dbSound != null) {
                PersistenceManager.getInstance().removeSound(dbSound);
            }
            this.dialog.hide();

        }
    }

    if (WindowEvent.WINDOW_HIDING.equals(event.getEventType())) {
        if (this.mediaPlayer != null) {
            this.mediaPlayer.stop();
        }
        SoundDataProxy.getInstance().storeSound(ApplicationUIConstants.SOUND_INFO, oriSound);
    }
}

From source file:com.tesshu.subsonic.client.sample4_music_andmovie.StreamPlayMovieApplication.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("CORPSE BRIDE", // query, required = true
            0, // artistCount, required = false
            null, // artistOffset, required = false
            0, // albumCount, required = false
            null, // albumOffset, required = false
            10, // songCount, required = false
            null, // songOffset, required = false
            null // musicFolderId, required = false
    );/*  w w w  .  j  av  a2 s . c o  m*/

    Child movie = result2.getSongs().stream().filter(child -> MediaType.VIDEO == child.getType())
            .filter(child -> format.equals(child.getSuffix())).collect(Collectors.toSet()).iterator().next();

    LOG.info(ToStringBuilder.reflectionToString(movie, ToStringStyle.MULTI_LINE_STYLE));

    // not valid?(Perhaps, I have not done convert setting on the server side)
    @SuppressWarnings("unused")
    String size = Integer.toString(movie.getOriginalWidth()) + "x"
            + Integer.toString(movie.getOriginalHeight());

    final IRequestUriObserver uriCallBack = (subject, uri) -> {
        uriStr = uri.toString();
    };

    streamController.stream(

            movie, // id
            null, // maxBitRate
            format, // format
            null, // timeOffset
            null, // size
            true, // estimateContentLength
            false, // converted
            null, // streamCallback
            uriCallBack, callback);

    Group root = new Group();
    Scene scene = new Scene(root, movie.getOriginalWidth(), movie.getOriginalHeight());
    Media media = new Media(uriStr);
    media.errorProperty().addListener((observable, old, cur) -> {
        LOG.info(cur + " : " + uriStr);
    });

    MediaPlayer player = new MediaPlayer(media);
    player.statusProperty().addListener((observable, old, cur) -> {
        LOG.info(cur + " : " + uriStr);
    });

    MediaView view = new MediaView(player);
    ((Group) scene.getRoot()).getChildren().add(view);
    stage.setScene(scene);
    stage.show();
    player.play();

}

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   ww w .jav a2s .  c om*/

    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();/*from w ww  .j a va 2s.  co  m*/

    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);//from  w ww. j  a v  a  2  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:com.spankingrpgs.scarletmoon.loader.EventLoader.java

/**
 * Constructs a media object from a music file name, and stores it in the {@link MusicMap}.
 *
 * @param music  The music file to turn into media
 *
 * @return The name of the song that was just stored
 *///from   ww w .  j a  v  a 2s  .  c  o m
private String hydrateMusic(JsonNode music) {
    if (music == null) {
        return null;
    }
    String musicName = music.asText();
    MusicMap musicMap = MusicMap.INSTANCE;
    if (musicMap.containsKey(musicName)) {
        return musicName;
    }
    //ogg is not supported
    List<String> types = Arrays.asList(".mp3", ".wav");
    Optional<String> musicFileName = types.stream()
            .map(type -> Paths.get(gameRoot, "data", "music", music.asText() + type)).map(Path::toString)
            .map(File::new).filter(File::exists).map(File::toURI).map(URI::toString).findFirst();

    if (!musicFileName.isPresent()) {
        LOG.warning(String.format("Music %s not found.", musicFileName));
        return musicName;
    }
    Media media = new Media(musicFileName.get());
    musicMap.put(musicName, media);
    return musicName;
}

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  ww w . jav  a  2 s. co m*/

    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;//from   w  w  w  . java  2 s .c o m
    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 ava2  s.co 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();
        }
    }
}