1

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.

np_6
  • 514
  • 1
  • 6
  • 19
dantheman
  • 11
  • 1
  • When something is included within the JAR file it is a "resource". Resources are conceptually not files, which means you should not try to access them via `java.io.File` or `java.nio.file.*`. Use the resource API provided by Java to get a URL to the resource (e.g. `Class#getResource(String)`) then pass that URL to `AudioSystem#getAudioInputStream(URL)`. Note if `Class#getResource(String)` is returning `null` then either you passed the wrong argument or the resource is not being included with your JAR file. – Slaw Apr 10 '21 at 12:55

1 Answers1

0

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")
Dahlin
  • 157
  • 1
  • 11
  • This is not sufficient. The developer first needs to ensure that the .WAV file is in the .JAR file (e.g., put it in a "resources" directory or something; I don't use Eclipse, so I don't know the correct incantation) and then get a reference to it with `Class.getResource()`. – Gene McCulley Apr 09 '21 at 17:14
  • I created a source folder called "MusicPlayer" where I put the .wav song file. This source folder isn't in the src file because eclipse would share error signs again. That's why I created the src and the source folder separately in the project folder. When I'm trying to use URL and getclass().getResource(), I get another error signs that say this.clip = null. – dantheman Apr 09 '21 at 17:30
  • my bad, I thought I did it this way, I edited my answer – Dahlin Apr 09 '21 at 17:58