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)
广告

© . All rights reserved.