How-To's > How do I control playback from code?


Use the following instance variables and functions of the MediaPlayer class to control media playback in your application:

  • pause() - Pauses playing.
  • play() - Starts or resumes playing.
  • stop() - Stops playing, resets to the beginning of the media, and resets the play count.
  • autoPlay - If autoPlay is true, playing will start as soon as possible.
  • paused - Indicated if the player has been paused, either programmatically, by the user, or because the media has finished playing.

Consider the following code fragment. It creates a simple player and controls its playback by using a control button.

import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;

def media = Media {source: "http:///"};

var player = MediaView {
    mediaPlayer: MediaPlayer {
        autoPlay: true //the media starts as soon as possible
        repeatCount: MediaPlayer.REPEAT_FOREVER //infinite time cycle for the media
        media: bind media
    }

};

def imagePlay = Image {url: "{__DIR__}buttonPlay.png"};
def imagePause = Image {url: "{__DIR__}buttonPause.png"};

var controlButton = ImageView {
    image: bind if (player.mediaPlayer.paused)
        then imagePlay
        else imagePause
    onMouseClicked: function (e) {
        if (player.mediaPlayer.paused){
        // resume or start playing if the player is paused
        player.mediaPlayer.play();
        }
        else {
        // pause playing if the player is run
        player.mediaPlayer.pause();
        }
    }
};

Stage {
    title: "Embedded Player"
    scene: Scene {
        width: 200
        height: 100
        content: [
        //you can arrange the player and the button,
        //add effects or animation
            player,
            controlButton
        ]
    }
}  

Tips

  • You can use any extension of the Node class to create a control component. The previous example uses the ImageView class to render a prefabricated image of a play/pause button. However, you can also construct the button by using graphical primitives of the javafx.scene.shape package.

Examples

API Documentation

Last Updated: April 2010
[Return to How-To's Home]