JavaFX - MediaPlayer getVolume() Method



In JavaFX, the getVolume() method of the 'MediaPlayer' class retrieves the current audio playback volume. This volume is represented by value between 0.0 and 1.0, where 0.0 signifies silence (muted) and 1.0 denotes maximum volume.

To use this method, we first need to create a 'MediaPlayer' instance and load a media file. Once the media file has been loaded and playback has started, we can call the 'getVolume()' method on the 'MediaPlayer' instance to retrieve the current volume level. By default, the volume level is set to 1.0, which is the maximum volume.

Syntax

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

public final void setVolume(double value)

Parameters

This method does not takes any parameters.

Return value

This method returns a 'double' value representing the current volume level of the media player ranging (from 0.0 to 1.0).

Example

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

In this example, we are using the 'getVolume()' method to display the volume level of the media file.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
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 GetVolumeExample 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);

      // creating a MediaView object from the MediaPlayer Object
      MediaView viewmedia = new MediaView(mediaPlayer);
      viewmedia.setFitHeight(455);
      viewmedia.setFitWidth(500);

      // Create a VBox to hold the label
      VBox root = new VBox();

      // Play the media to ensure it's loaded and obtain the volume level
      mediaPlayer.setOnReady(() -> {
         // Get the volume level using getVolume() method
         double volumeLevel = mediaPlayer.getVolume();
         Label volumeLabel = new Label("Volume Level: " + volumeLevel);
         root.getChildren().add(volumeLabel);
      });

      mediaPlayer.play();

      root.getChildren().addAll(viewmedia);
      Scene scene = new Scene(root, 550, 270);

      // Set the Scene to the Stage
      primaryStage.setScene(scene);
      primaryStage.setTitle("GetVolume Example");
      primaryStage.show();
   }
   public static void main(String[] args) {
      launch(args);
   }
}

Output

Following output of the code displays the volume label in a VBox at the bottom of the video.

getVolume
Advertisements