如何使用MediaPlayer在JavaFX中播放mp3文件?

时间:2019-01-09 20:49:08

标签: java javafx javafx-8 media

我已经尝试过这种方式:

@FXML
void playButtonFunction() throws URISyntaxException {
    final int selectedIdx = listView.getSelectionModel().getSelectedIndex();
    if (selectedIdx != -1) {
        Media pick = new Media("file:%2F%2F" + arrayList.get(selectedIdx).getPath().replaceAll(" ","%20")); // replace this with your own audio file
        mediaPlayer = new MediaPlayer(pick);
        mediaPlayer.play();
    }
}

但是我遇到了java.lang.IllegalArgumentException:

Exception in thread "Thread-5" java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.<init>(File.java:418)
at com.sun.media.jfxmedia.locator.ConnectionHolder$FileConnectionHolder.openFile(ConnectionHolder.java:216)
at com.sun.media.jfxmedia.locator.ConnectionHolder$FileConnectionHolder.<init>(ConnectionHolder.java:175)
at com.sun.media.jfxmedia.locator.ConnectionHolder.createFileConnectionHolder(ConnectionHolder.java:62)
at com.sun.media.jfxmedia.locator.Locator.createConnectionHolder(Locator.java:600)
at com.sun.media.jfxmediaimpl.MetadataParserImpl.run(MetadataParserImpl.java:102)

我也尝试了一个文件对象:

File file = new File(arrayList.get(selectedIdx).getPath());
Media pick = new Media(ClassLoader.getSystemResource(file.getName()).toExternalForm());
mediaPlayer = new MediaPlayer(pick);
mediaPlayer.play();

但是后来我得到了

java.lang.reflect.InvocationTargetException

我不知道如何调试它。

0 个答案:

没有答案