Reputation: 11
I want to create a game and it should include music which is playing in the background. The music file is a .wav file in a Source Folder.
How can I play music in an executable jar file with my code in the main method:
public class PlayMusic {
public static void main(String[] args) throws LineUnavailableException, IOException, UnsupportedAudioFileException, InterruptedException {
File file = new File("MusicPlayer/SnakeOST.wav");
AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
clip.start();
clip.loop(Clip.LOOP_CONTINUOUSLY) ;
}
}
This code does work in Eclipse, but after exporting the code there's music missing in the .jar file.
Upvotes: 1
Views: 138
Reputation: 177
your problem is, that your path is looking for a folder called MusicPlayer within your src folder. You want to use an absolute Path like:
/MusicPlayer/SnakeOST.wav
with this, the Path will begin at the root of the jar, then look for the folder called "MusicPlayer"
EDIT: You need a reference to your class, like:
App.class.getResourceAsStream("/model/test.png")
or
App.class.getResource("/model/test.png")
Upvotes: 0