JavaFX - Media getError() 方法



在 JavaFX 中,Media 類的 getError() 方法用於查詢在播放或載入媒體檔案時是否存在任何問題。當呼叫此函式時,它會返回遇到的錯誤型別,表示為 MediaError 列舉。

以下是 mediaError 列舉 -

  • UNKNOWN - 表示未知或未指定的錯誤。

  • MEDIA_UNSUPPORTED - 表示不支援媒體格式或編解碼器。

  • MEDIA_INACCESSIBLE - 表示媒體檔案或源不可訪問。

  • MEDIA_UNAVAILABLE - 表示媒體檔案或源不可用或找不到。

  • MEDIA_NETWORK_ERROR - 表示載入或播放媒體時發生的網路相關錯誤。

  • MEDIA_PLAYBACK_ERROR - 表示媒體播放過程中發生的錯誤。

語法

以下是 'Media' 類的 'getError()' 方法的語法 -

public MediaError getError()

引數

此方法不接受任何引數。

返回值

此方法返回媒體播放期間遇到的錯誤。如果沒有錯誤,則返回 null。

示例

以下是一個演示 getError() 方法的基本示例,其中我們提供了不存在的媒體檔案的路徑 -

在此示例中,我們檢索載入媒體時發生的任何錯誤。如果發生錯誤,此過程可能會丟擲 MediaException。如果未丟擲異常,則表示未發生錯誤。

import javafx.scene.media.Media;
import javafx.scene.media.MediaException;
import java.io.File;

public class GetError1 {
   public static void main(String[] args) {
      // Provide the path to a non-existent media file
      File mediaFile = new File("sample.mp4");
      try {
         Media media = new Media(mediaFile.toURI().toString());
         // This may throw a MediaException if an error occurs
         media.getError();
         // If no exception is thrown, it means no error occurred
         System.out.println("No error occurred.");
      } catch (MediaException e) {
         // Handle the MediaException gracefully
         System.out.println("Error occurred: " + e.getMessage());
         e.printStackTrace();
      }
   }
}

輸出

以下是在指定不正確路徑時程式碼中發生的錯誤。

Error occurred: D:\TP Work\javaFx api\Audio_Video_Class\sample.mp4 (The system cannot find the file specified)
MediaException: MEDIA_UNAVAILABLE : D:\TP Work\javaFx api\Audio_Video_Class\sample.mp4 (The system cannot find the file specified)
   at javafx.media@21.0.2/javafx.scene.media.Media.(Media.java:406)
   at GetError1.main(GetError1.java:13)
   at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
   at java.base/java.lang.reflect.Method.invoke(Method.java:580)
   at jdk.compiler/com.sun.tools.javac.launcher.Main.execute(Main.java:484)
   at jdk.compiler/com.sun.tools.javac.launcher.Main.run(Main.java:208)
   at jdk.compiler/com.sun.tools.javac.launcher.Main.main(Main.java:135)
廣告