0

Most of the solutions tells me use the File Class, but I am planning to use the audio stored in the Java Project. If I make an .exe file, would that work when I'm using File Class?

Dory
  • 5
  • 2
  • 2
    Use [`Class#getResource`](https://docs.oracle.com/javase/10/docs/api/java/lang/Class.html#getResource(java.lang.String)) or [`Class#getResourceAsStream`](https://docs.oracle.com/javase/10/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)) – MadProgrammer Dec 20 '19 at 23:08
  • You must not use File. Do not under any circumstances attempt to create a File object using the string returned by the getFile() method of the URL returned by Class.getResource. getFile() does not return a valid file name. Do as MadProgrammer said and read a resource URL or resource stream directly. For more information, see https://stackoverflow.com/questions/20389255/reading-a-resource-file-from-within-jar. – VGR Dec 21 '19 at 00:08

1 Answers1

1

If you are using JavaFX, there is direct support for MP3. I just discovered this page, and haven't tried using it yet. I've always used javax.sound.sampled.SourceDataLine for audio output, and added libraries as needed to deal with the compression format. There are some useful libraries on github: https://github.com/pdudits/soundlibs. Of these, I've only used the jorbis library for ogg/vorbis encoded wav files. But the mp3 decoders here have been around for a long time, have been used in countless projects, and should work.

As far as packaging audio resources, a key thing to remember is that file systems don't "see into" jar files. So, a File address is basically useless as long as the resource is packed into a jar. But a URL can specify a file that is jarred. The usual practice is to have a "resource" folder for the project that can be specified by a relative address, and to load the resource using its URL. The URL can be obtained using the .getResource method of Class

For example, if you have a class named "AudioHandler" in your project in a package loction "com.dory.mymediaplayer", and a sub folder "/res", and an mp3 file "audiocue01.mp3" in /res, the line to obtain the URL for the mp3 file would be as follows:

URL url = AudioHandler.getClass().getResource("res/audiocue01.mp3");

However, depending on the needs of the library used for decoding the mp3, you might need to use the .getResourceAsStream method. The getResourceAsStream method returns an InputStream instead of a URL.

Phil Freihofner
  • 7,645
  • 1
  • 20
  • 41