Search code examples
javajavafxmedia

How can I play an audio file from within a ZipFile using JavaFX Media and Mediaplayer?


I'm desperately trying to play an mp3 from inside of a zip file. Right now I'm making a TempFile and copying the data from the audio file in the zip

File songfile = File.createTempFile("audio", ".mp3");
Files.copy(zipFile.getInputStream(zipEntries.get(i)), songfile.toPath());
song = new Media(songfile.getPath());
songPlayer = new MediaPlayer(song);
songPlayer.play();

i cant seem to figure out what to do next, attempts to create a media with this temp file are falling flat.

I have tried to simply create a media with the temp file, but i guess i cant figure out the path for it? no matter what i do it gives me an absurd amount of errors.

The main problem seems to be the Files.copy. I'm getting a FileAlreadyExists error that seems to be the problem causer.


Solution

  • Ok! There were two issues plaguing this code. The first was that I was supplying the Media constructor with a Path when it needs a URI. This was solved by the following

    song = new Media(songfile.toURI().toString());

    The next issue was my FileAlreadyExists error. This was also a really simple fix, I just needing to set the CopyOption to REPLACE_EXISTING as following

    Files.copy(zipFile.getInputStream(zipEntries.get(i)), songfile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    

    Thats it! The song plays perfectly now!