Given that you have an Assets
folder in your project, you could do something like this:
initializeAudio("Assets/my_cool_song.wav");
where initializeAudio
relies on a class-level declaration of a Clip
object:
private void initializeAudio(final File url) {
try {
if (clip != null) stopPlay();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(url);
clip = AudioSystem.getClip();
clip.open(inputStream);
} catch (Exception e) {
stopPlay();
System.err.println(e.getMessage());
}
}
The reason that this works on all computers with the project (or JAR), and initializeAudio("/Users/myusername/Developer/Projects/AudioApp/Assets/my_cool_song.wave");
doesn't work is because one relies on a hard-coded absolute path, and the other relies on a file-path relative to the structure of the project. When creating relative paths, pretend that the base directory of your project is all that exists.
So, for example, if your project structure is a MyProject
folder with children Assets
, src
, bin
, and util
, and you wanted to refer to some item within the util
folder, pass along the path like so: util/my_cool_file.jpeg