JavaFX - MediaPlayer setRate() Method



In JavaFX, the setRate() method sets the playback rate of the media player. The playback rate determines how fast or slow the media is played.

The 'rate' lies between 0.0 and 8.0. If the media duration is set to Duration.INDEFINITE, invoking this method will not change anything.

Syntax

Following is the syntax of the 'setRate()' method of 'MediaPlayer' class −

public final void setRate(double value)

Parameters

This method takes one parameter.

  • value − A 'double' value representing the playback rate, where a playback rate of 1.0 equals normal speed. Higher rates speed up playback, while lower rates slow it down.

Return value

This method does not returns any value.

Example

Following is a basic example demonstrating the setRate() method of the MediaPlayer class −

In this example, we create an application where the video is playing with a playback rate of 1.5x on the StackPane.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
import java.io.File;

public class SetRateExample extends Application {
   @Override
   public void start(Stage primaryStage) {
      File mediaPath = new File("./audio_video/sampleTP.mp4");
      Media media = new Media(mediaPath.toURI().toString());

      MediaPlayer mediaPlayer = new MediaPlayer(media);
      // Set the playback rate to 1.5x
      mediaPlayer.setRate(1.5);
      // Create a MediaView to visualize the media
      MediaView mediaView = new MediaView(mediaPlayer);

      mediaView.setFitHeight(250);
      mediaView.setFitWidth(400);

      // Create a StackPane and add the MediaView to it
      StackPane stackPane = new StackPane();
      stackPane.getChildren().add(mediaView);
      // Create a Scene with the StackPane as the root node
      Scene scene = new Scene(stackPane, 550, 300);

      primaryStage.setScene(scene);
      primaryStage.setTitle("Media Player with Custom Rate");
      primaryStage.show();

      // Play the media
      mediaPlayer.play();
   }
   public static void main(String[] args) {
      launch(args);
   }
}

Output

Following output displays the media playing with a playback rate of 1.5x.

mPlayersetRate
Advertisements