I'm new to java programming and I'm trying to get audio to play when I export my java project into a runnable JAR file, but I keep getting an error when it tries to access the audio file as a JAR.
I've tried 2 different ways to get the audio to play (one is commented, and the other isn't). They both work in the compiler. The uncommented one gives me errors in the JAR file, while the commented one won't even run the JAR file!
InputStream in;
AudioStream as;
public void PlayMusic(boolean a)
{
try
{
if (a == false)
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(this.getClass().getResourceAsStream("./lose.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
/*in = getClass().getResourceAsStream("/connectfour/lose.wav");
as = new AudioStream (in);
AudioPlayer.player.start(as);*/
}
else
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(this.getClass().getResourceAsStream("./win.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
/*in = getClass().getResourceAsStream("/connectfour/win.wav");
as = new AudioStream (in);
AudioPlayer.player.start(as);*/
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Error");
}
}
I think I might be accessing the files incorrectly considering how it works perfectly fine in the compiler but not in the JAR.
EDIT: Solved. I found out about using urls, as they can work on jar files.
Try with:
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("./lose.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
where "./lose.wav" is the location of the audio file relative to the JAR file (and not to the main class or the src folder).