JavaFX - Media getSource() Method



In general, a media source refers to the origin or location of multimedia content, such as audio, or video. It defines the file, stream, or URL from which the media content is obtained or retrieved.

In JavaFX, the method getSource() of the 'Media' class is used to retrieve the source URI (Uniform Resource Identifier) of a media file.

Syntax

Following is the syntax of the 'getSource()' method of 'Media' class −

public String getSource()

Parameters

This method does not take any parameters.

Return value

This method returns a 'String' that represents the URI of the media source.

Example

Following is the basic example of the getSource() method −

In this example, we define a class named 'GetSource1'. Inside this class, we load the media, and to obtain the source of the media, we use the getSource() method.

import javafx.scene.media.Media;
import java.io.File;
public class GetSource1 {
   public static void main(String[] args) {
      // Provide the correct file path
      String filePath = "./audio_video/sampleTP.mp4";
      try {
         // Create a File object representing the media file
         File mediaFile = new File(filePath);

         // Convert the File object to a URI string
         String sourceURI = mediaFile.toURI().toString();
         Media media = new Media(sourceURI);

         // Get the source URI using getSource() method
         String sourceURIResult = media.getSource();
         System.out.println("Source URI: " + sourceURIResult);
      } catch (IllegalArgumentException e) {
         // Handle the exception gracefully
         System.err.println("Error loading media: " + e.getMessage());
         e.printStackTrace();
      }
   }
}

Output

Following is the output of the code displays the source of the specified video file.

Source URI: file:/D:/Audio_Video_Class/./audio_video/sampleTP.mp4
Advertisements