How can I play an mp3 file in JavaFX using MediaPlayer?

I've tried this way:

@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();

}

}

but I got an java.lang.IllegalArgumentException:

Exception in thread "Thread-5" java.lang.IllegalArgumentException: URI is not hierarchical

at java.io.File.(File.java:418)

at com.sun.media.jfxmedia.locator.ConnectionHolder$FileConnectionHolder.openFile(ConnectionHolder.java:216)

at com.sun.media.jfxmedia.locator.ConnectionHolder$FileConnectionHolder.(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)

Also I tried with a file object:

File file = new File(arrayList.get(selectedIdx).getPath());

Media pick = new Media(ClassLoader.getSystemResource(file.getName()).toExternalForm());

mediaPlayer = new MediaPlayer(pick);

mediaPlayer.play();

but then I got an

java.lang.reflect.InvocationTargetException

and I don't know how could I debug it....

Read More »

By: StackOverFlow - Wednesday, 9 January

Related Posts