Adil
Adil

Reputation: 4623

Play consecutive videos in JavaFX

I want to play tow (or more) videos that exists in my hard disk, how can I update the Media object so that the MediaPlayer go to next video automaticlly.

Upvotes: 2

Views: 6745

Answers (2)

jewelsea
jewelsea

Reputation: 159576

Here is a sample program which plays an AudioPlaylist from the hard drive.

The program works by creating a list containing a new MediaPlayer and a new Media for each file to be played. There is a single MediaView in the program and, for each MediaPlayer, onEndOfMedia the MediaView's MediaPlayer is set to the next one in the list. It's pretty much the same solution as jju's recursive answer.

Note, to change the playing Media, you don't update the Media in the MediaPlayer (there is no way to do that as there is a 1:1 correspondence between Media and MediaPlayer), instead you update the MediaPlayer in the MediaView.

The concept for Videos is pretty much the same as Audio because both Audio and Video in JavaFX are represented as Media played by a MediaPlayer and managed through a MediaView.

Upvotes: 1

Jju
Jju

Reputation: 135

Now i can't test it, but i think it should work:

public MediaView createMediaView(Collection<String> urls){
    MediaView mediaView = new MediaView();
    initMediaPlayer(mediaView, urls.iterator());
    return mediaView;
}

private void initMediaPlayer(
          final MediaView mediaView, 
          final Iterator<String> urls
){
    if (urls.hasNext()){
        MediaPlayer mediaPlayer = new MediaPlayer(new Media(urls.next()));
        mediaPlayer.setAutoPlay(true);
        mediaPlayer.setOnEndOfMedia(new Runnable() {
            @Override public void run() {
                initMediaPlayer(mediaView, urls);
            }
        });
        mediaView.setMediaPlayer(mediaPlayer);
    } 
}

Upvotes: 2

Related Questions