0

I want to load meta data from an MP3 file, to be played by a JavaFx MediaPlayer. This works fine in the unit test, but not in the application. In the unit test, 6 items of metaData reported, but zero in the application. The method that "does the work" is the same.

The main class of the application extends Application. The test class extends ApplicationTest from TestFx. Could that affect the behavior?

The application:

public class MediaMain extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {

        Map<String, Object> meta = metaData();

        System.out.printf("Number of meta data: %d.%n", meta.size());
        System.out.println(meta);
    }

    Map<String, Object> metaData() {
        File audioFile = new File("src/main/resources", "beingBoiled.mp3");
        final URI uri = audioFile.toURI();
        final String source = uri.toString();
        Media media = new Media(source);
        new MediaPlayer(media);
        return media.getMetadata();
    }
}

The unit test:

class MediaMainTest extends ApplicationTest {

    @Test
    void testMeta() {
        MediaMain main = new MediaMain();

        Map<String, Object> metaData = main.metaData();

        assertNotEquals(0, metaData.size());
        System.out.printf("Number of meta data: %d.%n", metaData.size());
        System.out.println(metaData);
    }
}

Printout from the application:

Number of meta data: 0.
{}

Printout from the unit test:

Number of meta data: 6.
{year=1980, artist=The Human League, raw metadata={ID3=java.nio.HeapByteBufferR[pos=254 lim=3214 cap=3214]}, album=Travelogue, genre=(52), title=Being Boiled}

What could be the reason? It's a mystery to me. Written with Java 11, JavaFx 11.0.2 and TestFx 4.0.15-alpha.

4

1 回答 1

0

您正在引用位置为 的文件src/main/resources,这可能不是一个好主意,因为您部署的应用程序可能没有src/main/resources目录,而且资源可能捆绑在应用程序 jar 中而不是作为磁盘上的文件,因此使用访问它的文件协议不起作用。

最好使用以下内容:

String mediaLoc = getClass().getResource("/beingBoiled.mp3").toExternalForm()
Media media = new Media(mediaLoc)

就像如何在 javafx8 中加载 css 文件一样。要加载的资源的确切位置可能因构建和项目结构而异。如果您不想从类路径加载,而是通过文件或通过网络 http 调用加载,那么您需要使用其他东西。

上面的代码假定您的构建系统设置为将媒体从src/main/resources您的目标打包位置复制到目标打包位置,并将资源打包到 jar 文件根目录中的应用程序可分发(例如应用程序 jar 文件)中。

确保您的构建系统实际上正在将文件复制到目标位置。您可以通过运行构建来检查它是否存在,查看生成的 jar 并运行jar tvf <myjarfilename>.jar以查看 mp3 资源是否位于 jar 文件根目录的正确位置。

于 2019-10-10T19:54:33.687 回答