简体   繁体   中英

How can JavaFX Media read .mp3 files inside runnable .jar file?

I have trouble getting my Java application with a JavaFX MediaPlayer to read the .mp3 file that is embedded in the runnable .jar output file.

I have tried every single solution from Google, eg toURL , toURI . Some of the solutions worked (the music was read and played) when I ran the program in Eclipse JVM but all of them failed when the code and the music were packed into a runnable .jar .

The .mp3 file I am going to read is located:

In Eclipse: Java Project --> src --> img --> music.mp3

In File Explorer: C:\\Users\\Me\\Desktop\\Java Project\\src\\img\\music.mp3 .

  • The following code worked in Eclipse JVM but failed when I executed the .jar.

     media_player = new MediaPlayer(new Media( Game.class.getClassLoader().getResource("img/music.mp3").toString())); 
  • System.out.println() of the above string gave me the following string in the Eclipse console:

     file:/C:/Users/Me/Desktop/Java%20Project/bin/img/music.mp3 

As I need to distribute the runnable .jar, I do not want to separate the .mp3 file from the .jar because it may cause inconvenience to the users.

Please tell me if the JavaFX Media or MediaPlayer are not supposed to handle this situation.

EDIT:

After reading the comments, it seemed that I had to choose Extract required libraries into generated JAR instead of Package required libraries into generated JAR when exporting the runnable .jar.

However, this raised another problem. ProGuard, the Java obfuscator I was using, could not process the libraries and prompted me duplicate definition of library class errors. I was forced to choose the third option, Copy required libraries into a sub-folder next to the generated JAR which allowed the music to be played but it resulted in all external libraries being separated from the .jar.

Is there another way of getting the obfuscator to work, external libraries to be embedded into the .jar and the music to be played?

Although I have not managed to solve this problem, I tried another approach to play .mp3 files inside the JAR and use ProGuard to obfuscate the code.

The solution was to use an external library, JLayer Player by JavaZOOM, instead of JavaFX.

When you create an executable jar file, a library file is also created in the same drive where the jar file is. However the important point to note is that you have to physically place the media file say eg song.mp3 in the directory and the jar file will execute....!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM